CAPÍTULO 3. PRONÓSTICO DE HUBBERT E HIDROCARBUROS NO
3.4 Yacimientos convencionales y no convencionales
You want to be able to communicate with a WebSocket server as a client.
Solution
There are several ways to connect to a WebSocket connection, and you will see two of these methods in this solution. One way to accomplish this is to utilize the third-party framework, WebSocket-Node, to create a client application that will connect to a WebSocket server and communicate between the two endpoints. This is shown in Listing 8-2 and is different than the more typical approach of utilizing a web page (which you will cover in more detail in Section 8-5) to connect to a WebSocket server and continue to communicate using that protocol.
Listing 8-2. Creating a WebSocket Client with WebSocket-Node /**
* A WebSocket Client */
var WebSocketClient = require('websocket').client; var client = new WebSocketClient();
client.on('connectFailed', function(error) {
console.log('Connect Error: ' + error.toString()); });
client.on('connect', function(connection) {
console.log('woot: WebSocket client connected'); connection.on('error', function(error) {
console.log(error); });
connection.on('close', function() {
console.log('echo-protocol Connection Closed'); });
connection.on('message', function(message) { switch (message.type) {
case 'utf8':
console.log('from server: ', message.utf8Data); break; default: console.log(JSON.stringify(message)); break; } }); connection.send('heyo'); }); client.connect('ws://localhost:8080/', 'echo-protocol');
Chapter 8 ■ Creating a WebSoCket Server
As an alternative to the WebSocket-Node implementation in Listing 8-2, you could create a WebSocket client that will connect by using an HTML page like the one shown in Listing 8-3.
Listing 8-3. WebSocket Client HTML Page <!doctype html> <html> <head> </head> <body> <h3>WebSockets!</h3> <script> window.onload = function() {
var ws = new WebSocket('ws://localhost:8080', 'echo-protocol'); ws.onopen = function() {
console.log('opened'); };
ws.onmessage = function(event) { console.log(event);
ws.send(JSON.stringify({ status: 'ok'})); }; }; </script> </body> </html>
How It Works
First, you created a client by using the WebSocketClient that is available to be used in a Node.js application that comes with WebSocket-Node. This client creates the upgraded connection to a WebSocket server for you when you call new WebSocketClient();. This constructor function will accept an options object and extend that with the default options, which are shown in Table 8-2.
Table 8-2. WebSocketClient Options
Option
Description
.assembleFragments This tells the client to automatically assemble fragmented frames into a complete message.
Default: true
.closeTimeout This is the time to wait, in milliseconds, until the connection is closed after not receiving a response.
Default: 5000
.disableNagleAlgorithm This tells whether to disable the Nagle algorithm, which will set a small delay before sending messages in order to reduce HTTP traffic.
Default: true
.fragmentOutgoingMessages This will cause outgoing messages that are larger than the set .fragmentationThreshold to be fragmented.
Chapter 8 ■ Creating a WebSoCket Server
Once you have created your WebSocket client, you are able to listen for events and messages that are transported via the connection. In your solution, you listen for a ‘connect' event. This event will receive the connection object in the callback, which you will then use to transmit and receive data to the server. The connection is initialized by calling the .connect() function on the WebSocket client. This will accept the URL and the protocol that you wish to bind the endpoints to.
To transmit a message to the WebSocket server, you utilize the connection.send() method. This method will take two arguments: first the data you wish to send, and second, a callback function (which is optional). The data will be processed to check whether the data are a buffer. If the data are a buffer, they will be processed by calling the .sendBytes() method of the connection; otherwise it will attempt to use the connection’s .sendUTF() method if the data can be converted with the .toString() method. The .sendBytes() or .sendUTF() methods will be where your callback is passed. You can see the internal workings of the WebSocket-Node implementation of the send method in Listing 8-4. Listing 8-4. WebSocketClient Send Method
WebSocketConnection.prototype.send = function(data, cb) { if (Buffer.isBuffer(data)) {
this.sendBytes(data, cb); }
else if (typeof(data['toString']) === 'function') { this.sendUTF(data, cb);
} else {
throw new Error("Data provided must either be a Node Buffer or implement toString()") }
};
You were also able to listen to the ‘message’ event. This event is emitted from the WebSocket server and in your example, you checked to see what type of message is received. Checking the type allows you to process the message appropriately, whether it is a utf8 string or another format. Using the WebSocketClient that comes with WebSocket-Node is a great way to build interprocess communications for your Node.js applications. However, you may want to use an HTML page to create your WebSocket clients.
By utilizing either the WebSocketClient or the native WebSockets available in the WebSocket object in a web browser, you can create a useful client connection to a WebSocket server.
Option
Description
.fragmentationThreshold This is the size limit at which to split frames into fragments. Default: 16KB
.webSocketVersion This is the specified version of the WebSocket protocol to utilize in this connection. Default: 13
.maxReceivedFrameSize This will set the maximum size of the frames that are received via the WebSocket protocol.
Default: 1 MB
.maxReceivedMessageSize This is the maximum size of the messages received via the protocol. It only applies if the .assembleFragments option is set to true.
Default: 8 MB
.tlsOptions This object can contain Transport Layer Security (TLS) information for secure connections.