问题描述
我已使用 Node.js 创建了一个用于监听客户端连接的 TCP服务器.我需要在Node.js中再次将数据从 TCP服务器 传输到 HTTP服务器 ,可能是通过 Websocket ( socket.io ).
I have created a TCP server using Node.js which listens to clients connections.I need to transmit data from TCP server to HTTP server again in Node.js possibly through a Websocket (socket.io).
但是,我不知道如何创建这样的连接,以使TCP服务器能够通过Websocket将数据推送到HTTP服务器.
However, I do not know how to create such connection such that TCP server is able to push data to HTTP server through Websocket.
非常感谢.
推荐答案
我正在尝试很多事情来完成这项工作.在大多数情况下,我都是依靠 socket.io 来实现此功能的,但是它不能与TCP一起使用.
I was trying lot of things to get this work. Most of the time I was relying on socket.io to get this working, but it was just not working with TCP.
但是, net.Socket 足以满足目的.
这是它的有效示例.
TCP服务器
var net = require('net');
var HOST = 'localhost';
var PORT = 4040;
var server = net.createServer();
server.listen(PORT, HOST);
server.on('connection', function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
sock.write("TCP sending message : 1");
console.log('Server listening on ' + server.address().address +':'+
server.address().port);
}).listen(PORT, HOST);
HTTP服务器
var http = require('http').createServer(httpHandler),
fs = require("fs"),
wsock = require('socket.io').listen(http),
tcpsock = require('net');
var http_port = 8888;
var tcp_HOST = 'localhost';
var tcp_PORT = 4040;
/**
* http server
*/
function httpHandler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
http.listen(http_port);
console.info("HTTP server listening on " + http_port);
wsock.sockets.on('connection', function (socket) {
var tcpClient = new tcpsock.Socket();
tcpClient.setEncoding("ascii");
tcpClient.setKeepAlive(true);
tcpClient.connect(tcp_PORT, tcp_HOST, function() {
console.info('CONNECTED TO : ' + tcp_HOST + ':' + tcp_PORT);
tcpClient.on('data', function(data) {
console.log('DATA: ' + data);
socket.emit("httpServer", data);
});
tcpClient.on('end', function(data) {
console.log('END DATA : ' + data);
});
});
socket.on('tcp-manager', function(message) {
console.log('"tcp" : ' + message);
return;
});
socket.emit("httpServer", "Initial Data");
});
浏览器客户端
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('httpServer', function (data) {
console.log(data);
document.write(data + "\r\n");
socket.emit('tcp', "For TCP");
});
</script>
这样,Node.js中的HTTP服务器和TCP服务器之间打开了一个套接字.
This way, there is a socket opened between HTTP server and TCP server in Node.js.
这篇关于在node.js中的TCP服务器和HTTP服务器之间创建WebSockets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!