我看到有一个新版本的 dart:io。如何使用新的 v2 dart:IO 创建一个套接字服务器,它侦听端口以获取新数据并通过 Web 套接字将接收到的数据推送到其订阅的客户端?
我有一个 java 和 ac# 桌面应用程序(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);