Question

I saw there is a new version of dart:io. How do I create a socket server with the new v2 dart:IO that listens to a port for new data and pushes the received data via Web Sockets to its subscribed clients?

I have a java and a c# desktop application (tcpClient) and I would like to send a string (json or xml) to my dart server on a specific port. That string should be replied to my tcpClient and pushed with Web Sockets to all other subscribed clients(browsers).

I have the following, but how do I access the data that has been sent to that specific socket?

import 'dart:io';

main() {ServerSocket.bind("127.0.0.1", 5555).then((ServerSocket socket) {
  socket.listen((Socket clientSocket) {

    //how to access data (String) that was 
    //send to the socket from my desktop application
  });
});
}

edit: maybe I should split the question in 2 parts.

How to create a Server in Dart that listens on a specific port for data?

In node.js one could use something like the following:

var net = require('net');

var HOST = '127.0.0.1';
var PORT = 6969;

// Create a server instance, and chain the listen function to it
// The function passed to net.createServer() becomes the event handler for the 'connection' event
// The sock object the callback function receives UNIQUE for each connection
net.createServer(function(sock) {

    // We have a connection - a socket object is assigned to the connection automatically
    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);

    // Add a 'data' event handler to this instance of socket
    sock.on('data', function(data) {

        console.log('DATA ' + sock.remoteAddress + ': ' + data);
        // Write the data back to the socket, the client will receive it as data from the server
        sock.write('You said "' + data + '"');

    });

    // Add a 'close' event handler to this instance of socket
    sock.on('close', function(data) {
        console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
    });

}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);
Was it helpful?

Solution

This is a partial answer, it only addresses how to create a server that will listen for client WebSocket connections.

Have you seen the WebSocketTransformer class?

WebSocketTransformer

I haven't had a chance to try this yet - but I think it's something like this:

HttpServer.bind(...).then((server) {
     server.transform(new WebSocketTransformer()).listen((webSocket) => ... );
});

Also see this discussion on the Dart mailing list.

OTHER TIPS

You could write a bridging software to transform incoming data from TCP socket and process the the data if necessary. Then send/broadcast the data through open WebSocket connection(s).

It is bit of work involving reading up the document for websocket spec. And then code it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top