Javascript Node.js 和 Socket.IO 广播服务器
我只需要一个简单的示例来解释如何创建 Node.JS 服务器。
基本上 Node.JS 将有 2 个服务器运行: - 一个粗糙的 TCP 服务器和 - Socket.IO 服务器 目的是将数据从 TCP 客户端转发到对其感兴趣的各种 Socket.IO 客户端。
这样做的原因是为了方便与其他语言的通信(我将有一个 java 服务器在 tcp 套接字中发送消息,因为我找不到更好的方法来做到这一点 - 所有可用的 java 库(socket.io 服务器和用 java 实现的客户端)都有错误),因为几乎每种语言都有套接字 api。
TCP 客户端将在连接后立即发送一个字符串,Node.JS 服务器将使用它创建一个命名空间并为其提供数据,因此 Socket.IO 客户端必须能够接收服务器从 TCP 客户端转发的数据。
步骤:
侦听 TCP 连接
在新的 TCP 连接上从客户端接收字符串
创建一个 Socket.IO 服务器,其名称空间名为 tcp 客户端提供的字符串
开始从 TCP 客户端接收数据并将其广播到所有客户端连接到命名空间的 Socket.IO 客户端在此套接字打开时创建
这必须以各种 TCP 客户端和Socket.IO 客户端可以进行通信,
我找不到如何以有效的方式做到这一点,如果有人可以提供一个简单的示例,我相信这会对很多人有所帮助(因为 Node.JS 和 Socket.IO 缺乏文档)并且这个对于已经知道的人来说很容易制作主题。
谢谢。
更新:
我做到了:
node.js代码:
var javaPort = 8080;
var sIOPort = 8081;
var javaServer = require('net').createServer();
var browserServer = require('socket.io').listen(sIOPort);
console.log('Socket.IO version: ' + require('socket.io').version);
javaServer.on('listening', function () {
console.log('Server is listening on ' + javaPort);
});
javaServer.on('error', function (e) {
console.log('Server error: ' + e.code);
});
javaServer.on('close', function () {
console.log('Server closed');
});
javaServer.on('connection', function (javaSocket) {
var clientAddress = javaSocket.address().address + ':' + javaSocket.address().port;
console.log('Java ' + clientAddress + ' connected');
var firstDataListenner = function (data) {
console.log('Received namespace from java: ' + data);
javaSocket.removeListener('data', firstDataListenner);
createNamespace(data, javaSocket);
}
javaSocket.on('data', firstDataListenner);
javaSocket.on('close', function() {
console.log('Java ' + clientAddress + ' disconnected');
});
});
javaServer.listen(javaPort);
function createNamespace(namespaceName, javaSocket) {
var browserConnectionListenner = function (browserSocket) {
console.log('Browser Connected');
var javaSocketDataListenner = function(data) {
console.log('Data received from java socket and sent to browser: ' + data);
browserSocket.emit('m', data + '\r\n');
}
var javaSocketClosedListenner = function() {
console.log('The java socket that was providing data has been closed, removing namespace');
browserSocket.disconnect();
browserServer.of('/' + namespaceName).removeListener('connection', browserConnectionListenner);
javaSocket.removeListener('data', javaSocketDataListenner);
javaSocket.removeListener('close', javaSocketClosedListenner);
}
javaSocket.on('close', javaSocketClosedListenner);
javaSocket.on('data', javaSocketDataListenner);
browserSocket.on('disconnect', function () {
console.log('Browser Disconnected');
javaSocket.removeListener('data', javaSocketDataListenner);
javaSocket.removeListener('close', javaSocketClosedListenner);
});
}
var namespace = browserServer.of('/' + namespaceName).on('connection', browserConnectionListenner);
}
java代码:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
try {
Socket nodejs = new Socket("localhost", 8080);
sendMessage(nodejs, "testnamespace");
Thread.sleep(100);
int x = 0;
while (true)
{
sendMessage(nodejs, x + "");
x++;
Thread.sleep(1000);
System.out.println(x + " has been sent to server");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendMessage(Socket s, String message) throws IOException {
s.getOutputStream().write(message.getBytes("UTF-8"));
s.getOutputStream().flush();
}
public static String readMessage(Socket s) throws IOException {
InputStream is = s.getInputStream();
int curr = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((curr = is.read()) != -1) {
if (curr == '\n') {
break;
}
baos.write(curr);
}
return baos.toString("UTF-8");
}
}
html代码:
<html>
<head>
<script src="socket.io.js"></script>
</head>
<body>
<script>
var socket = io.connect("http://localhost/testnamespace", {port: 8081});
console.log(io.version);
socket.on('connect', function () {
console.log('Connected');
});
socket.on('m', function (msg) {
console.log('Message received: ' + msg);
});
socket.on('disconnect', function () {
console.log('Disconnected');
});
</script>
</body>
</html>
它是如何工作的:
Java通过TCP套接字连接没有nodejs然后发送命名空间名称,nodejs使用该命名空间创建一个socket.io服务器并转发所有消息java套接字发送到连接到该命名空间的所有 socket.io 客户端
如果有人看到错误或可以进行改进,请分享。
谢谢
I just need a simple example how to do a Node.JS server that I'll explain.
Basically Node.JS will have 2 servers running:
- A crude TCP server and
- A Socket.IO server
The objective is to forward data from a TCP Client to various Socket.IO clients interested in it
The reason to do this is to make easy to do the communication with other languages (I'll have a java server sending messages in a tcp socket, as I couldnt find a better way to do this - all available java libraries (socket.io server and clients implemented in java) are buggy) as almost every language has socket api.
The TCP client will send a string right after connect and the Node.JS server will create a namespace with it and provide data for it so Socket.IO clients must be able to receive the data that the server will forward from the TCP client.
Steps:
Listen for TCP connections
On a new TCP connection receive a string from the client
Create a Socket.IO server with a namespace named the string provided from tcp client
Start receiving data from TCP client and broadcast it to all the Socket.IO clients conected to the namespace that was created when this socket opened
This has to be made in a way that various TCP clients and Socket.IO clients can communicate
I cant find how to do this in a efficient way, if someone can provide a simple example I'm sure it would help a lot of ppl (as Node.JS and Socket.IO lacks documentation) and this is easy to make for ppl that already know of the subject.
Thanks.
UPDATE:
I made it:
node.js code:
var javaPort = 8080;
var sIOPort = 8081;
var javaServer = require('net').createServer();
var browserServer = require('socket.io').listen(sIOPort);
console.log('Socket.IO version: ' + require('socket.io').version);
javaServer.on('listening', function () {
console.log('Server is listening on ' + javaPort);
});
javaServer.on('error', function (e) {
console.log('Server error: ' + e.code);
});
javaServer.on('close', function () {
console.log('Server closed');
});
javaServer.on('connection', function (javaSocket) {
var clientAddress = javaSocket.address().address + ':' + javaSocket.address().port;
console.log('Java ' + clientAddress + ' connected');
var firstDataListenner = function (data) {
console.log('Received namespace from java: ' + data);
javaSocket.removeListener('data', firstDataListenner);
createNamespace(data, javaSocket);
}
javaSocket.on('data', firstDataListenner);
javaSocket.on('close', function() {
console.log('Java ' + clientAddress + ' disconnected');
});
});
javaServer.listen(javaPort);
function createNamespace(namespaceName, javaSocket) {
var browserConnectionListenner = function (browserSocket) {
console.log('Browser Connected');
var javaSocketDataListenner = function(data) {
console.log('Data received from java socket and sent to browser: ' + data);
browserSocket.emit('m', data + '\r\n');
}
var javaSocketClosedListenner = function() {
console.log('The java socket that was providing data has been closed, removing namespace');
browserSocket.disconnect();
browserServer.of('/' + namespaceName).removeListener('connection', browserConnectionListenner);
javaSocket.removeListener('data', javaSocketDataListenner);
javaSocket.removeListener('close', javaSocketClosedListenner);
}
javaSocket.on('close', javaSocketClosedListenner);
javaSocket.on('data', javaSocketDataListenner);
browserSocket.on('disconnect', function () {
console.log('Browser Disconnected');
javaSocket.removeListener('data', javaSocketDataListenner);
javaSocket.removeListener('close', javaSocketClosedListenner);
});
}
var namespace = browserServer.of('/' + namespaceName).on('connection', browserConnectionListenner);
}
java code:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
try {
Socket nodejs = new Socket("localhost", 8080);
sendMessage(nodejs, "testnamespace");
Thread.sleep(100);
int x = 0;
while (true)
{
sendMessage(nodejs, x + "");
x++;
Thread.sleep(1000);
System.out.println(x + " has been sent to server");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendMessage(Socket s, String message) throws IOException {
s.getOutputStream().write(message.getBytes("UTF-8"));
s.getOutputStream().flush();
}
public static String readMessage(Socket s) throws IOException {
InputStream is = s.getInputStream();
int curr = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((curr = is.read()) != -1) {
if (curr == '\n') {
break;
}
baos.write(curr);
}
return baos.toString("UTF-8");
}
}
html code:
<html>
<head>
<script src="socket.io.js"></script>
</head>
<body>
<script>
var socket = io.connect("http://localhost/testnamespace", {port: 8081});
console.log(io.version);
socket.on('connect', function () {
console.log('Connected');
});
socket.on('m', function (msg) {
console.log('Message received: ' + msg);
});
socket.on('disconnect', function () {
console.log('Disconnected');
});
</script>
</body>
</html>
How it works:
Java connect no nodejs over TCP socket then send a namespace name, nodejs create a socket.io server with that namespace and forward all messages java socket sends to all socket.io clients connected to that namespace
If anyone see errors or improvements that could be made please share.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我正在制作一个类似的应用程序,但我没有使用 TCP,而是在 TCP 之上使用 ZeroMQ。这段代码的工作原理非常简单。
在这里查看我的代码:
https://github.com/EhevuTov/netPeek
做:
我希望有帮助。
顺便说一句,我认为我的回调函数没有正确实现。我想每次传递消息时我都会设置 on 事件对象。如果您找到更好的方法,请提交带有修复的拉取请求。 :-)
I'm making a similar app, but instead of using TCP I'm using ZeroMQ on top of TCP. This code works very simply.
Check out my code here:
https://github.com/EhevuTov/netPeek
Do:
I hope that helps.
As a side note, I don't think my callback function is properly implemented. I think I'm setting the on event object every time a message gets passed. If you find a better way, please submit pull request with a fix. :-)