Communicating with WebSocket server using a TCP class

2.1k Views Asked by At

Would it be possible to send and receive data/messages/frames to and from a WebSocket server interface using a standard TCP class?

Or would I need to fundamentally change the TCP class?

If this is possible, could you show me a little example of how it could look like? (programming language doesn't really matter)
For example I found this node.js code which represents a simple tcp client:

var net = require('net');

var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
    console.log('Connected');
    client.write('Hello, server!');
});

client.on('data', function(data) {
    console.log('Received: ' + data);
});

Maybe you could show me what would have to be changed to make it communicate with a WebSocket.

1

There are 1 best solutions below

0
On BEST ANSWER

Websockets is a protocol that runs over TCP/IP, as detailed in the standard's draft.

So, in fact, it's all about using the TCP/IP connection (TCP connection class / object) to implement the protocol's specific handshake and framing of data.

The Plezi Framework, written in Ruby, does exactly that.

It wraps the TCPSocket class in it's wrapper called Connection (or SSLConnection) and runs the data through a Protocol input layer (the WSProtocol and HTTPProtocol classes) to the app layer and then through the Protocol output layer (the WSResponse and HTTPResponse classes) to the Connection:

 TCP/IP receive -> Protocol input layer ->
     App -> Protocol output -> TCP/IP send

A Websocket handshake always starts as an HTTP request. You can read the Plezi's handshake code here*.

* the handshake method receives an HTTPRequest, HTTPResponse and an App Controller and uses them to send the required HTTP reply before switching to Websockets.

Once the handshake is complete, each message received is made up of message frames (one or more). You can read the frame decoding and message extraction code used in the Plezi Framework here.

Before sending messages back, they are divided into one or more Websocket Protocol frames using this code and then they are sent using the TCP/IP connection.

There are plenty of examples out there if you google. I'm sure some of them will be in a programming language you prefer.