2013-03-10 38 views
1

我看到dart:io的新版本。如何使用新的v2 dart創建一個套接字服務器:爲接收新數據偵聽端口的IO,並通過Web套接字將接收的數據推送到其訂閱的客戶端?TCP套接字服務器,用於監聽端口並使用Web套接字推送數據

我有一個Java和C#桌面應用程序(TcpClient的),我想一個字符串(JSON或XML)發送到我的鏢服務器的特定端口上。該字符串應該被回覆給我的tcpClient,並用Web Sockets推送給所有其他訂閱的客戶端(瀏覽器)。

我有以下,但如何訪問已發送到特定的套接字的數據?

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 
    }); 
}); 
} 

編輯:也許我應該在2份分割的問題。

如何在Dart中創建一個偵聽特定端口上的數據的服務器?

在node.js的一個可以使用類似以下內容:

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); 

回答

2

這是一個局部的答案,只解決了如何創建一個將偵聽服務器客戶端WebSocket連接。

你見過WebSocketTransformer類嗎?

WebSocketTransformer

我還沒有機會尚未嘗試這一點 - 但我認爲這是這樣的:

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

另見this discussion達特郵件列表上。

0

你可以寫一個橋接軟件從TCP套接字變換輸入數據,如果需要處理的數據。然後通過打開的WebSocket連接發送/廣播數據。

這是一個涉及閱讀了文檔websocket spec工作位。然後編碼。