【问题标题】:TCP Socket Server that listens to a port and PUSHes data with Web Sockets侦听端口并使用 Web 套接字推送数据的 TCP 套接字服务器
【发布时间】:2013-03-10 00:46:31
【问题描述】:

我看到有一个新版本的 dart:io。如何使用新的 v2 dart:IO 创建一个套接字服务器,它侦听端口以获取新数据并通过 Web 套接字将接收到的数据推送到其订阅的客户端?

我有一个 java 和一个 c# 桌面应用程序 (tcpClient),我想在特定端口上向我的 dart 服务器发送一个字符串(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
  });
});
}

编辑:也许我应该把问题分成两部分。

如何在 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);

【问题讨论】:

    标签: dart dart-io


    【解决方案1】:

    这是一个部分答案,它只涉及如何创建一个将侦听客户端 WebSocket 连接的服务器。

    你见过 WebSocketTransformer 类吗?

    WebSocketTransformer

    我还没有机会尝试这个 - 但我认为它是这样的:

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

    另请参阅 Dart 邮件列表中的 this discussion

    【讨论】:

      【解决方案2】:

      您可以编写一个桥接软件来转换来自 TCP 套接字的传入数据,并在必要时处理数据。然后通过打开的 WebSocket 连接发送/广播数据。

      阅读websocket spec 的文档是一项工作。然后编码。

      【讨论】:

        猜你喜欢
        • 2015-09-23
        • 1970-01-01
        • 2015-01-20
        • 1970-01-01
        • 2016-06-07
        • 1970-01-01
        • 1970-01-01
        • 2017-07-20
        • 1970-01-01
        相关资源
        最近更新 更多