简体   繁体   English

无法将数据从一个客户端发送到socket.io Node.JS中的另一个客户端

[英]Unable to send data from one Client to another in socket.io Node.JS

I have two clients which can interchange some data over socket.io. 我有两个客户端,可以通过socket.io交换一些数据。 I also have a server. 我也有一台服务器。 What i need to do is i want to send data from client 1 to client 2 over a socket and i am unable to figure out that how i can achieve it.Please note that client 1 and client 2 are different html pages. 我需要做的是我想通过套接字将数据从客户端1发送到客户端2,但我无法弄清楚如何实现。请注意,客户端1和客户端2是不同的html页面。

Server.JS Server.JS

var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');

var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
var ip=process.env.IP||"192.168.1.5";
app.use(express.static(__dirname));
server.listen(port,ip, function () {
  console.log('Server listening at port %d ', port);
});
app.get('/index', function(req, res) {
  res.sendFile(path.join(__dirname,'/test.html'));
})
app.get('/index1', function(req, res) {
  res.sendFile(path.join(__dirname,'/test1.html'));
})

io.on('connection', function (socket) {
   socket.on('broadcast', function (message) {
            console.log(message);




            socket.broadcast.emit('message', message);
            });
            console.log("connected");

 });

Client1.JS 客户端1.JS

 <!doctype html>
<html lang="en">
<head>
</head>
<body>
 <script src="/socket.io/socket.io.js"></script>
 <script >
var socket = io.connect();
socket.emit('broadcast',"Broadcasting Message");
socket.on('message', function (data) {

     alert(data)
});
 </script>
  </body>

Client2.JS Client2.JS

 <!doctype html>
<html lang="en">
<head>
</head>
<body>
 <script src="/socket.io/socket.io.js"></script>
 <script >
var socket = io.connect();


socket.on('message', function (data) {

     alert(data)
    //socket.emit('message',"Hello world");
});
 </script>
  </body>

Ok, here is what I did on my local and you may change it by your needs. 好的,这是我在本地执行的操作,您可以根据需要进行更改。

server.js server.js

var io = require('socket.io')(80);

io.on('connection', function (socket) {
 socket.on('broadcast', function (message) {
        console.log(message);
        socket.broadcast.emit('message', message);
        });
        console.log("connected");

}); });

client1.js client1.js

var socket = io.connect('ws://127.0.0.1');
socket.emit('broadcast',"Broadcasting Message");
socket.on('message', function (data) {
     $('#client1').html(data);
});

client2.js client2.js

 var socket = io.connect('ws://127.0.0.1');
 socket.on('message', function (data) {
     $('#client2').html(data);
});

index.html index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src='https://code.jquery.com/jquery-1.12.4.min.js'></script>
    <script type="text/javascript" src="/socket.io/socket.io.js"></script>
    <script type="text/javascript" src="client1.js"></script>
    <script type="text/javascript" src="client2.js"></script>
</head>
<body>
        <div> <h1> CLIENT 1 </h1><div id="client1"></div></div>
        <div> <h1> CLIENT 2 </h1><div id="client2"></div></div>
</body>
</html>

On a termminal after you run, node server.js and reload your page, you will see client2 will have Broadcasting message html appended 在运行终端node server.js并重新加载页面后,您将看到client2将附加Broadcasting message html。

Make sure to pass the URL to the server when instantiating WS on the client side... for example var socket = io.connect('http://localhost'); 在客户端实例化WS时,请确保将URL传递给服务器...例如var socket = io.connect('http://localhost');

On the server side, each WS connection with each client is a unique instance. 在服务器端,与每个客户端的每个WS连接都是唯一的实例。 That is to say that for this purpose you must be deliberate about which WS connection you target when emitting events. 也就是说,为此,您必须仔细考虑在发出事件时要针对的WS连接。

The first thing to solve is how to associate WS connection instances with specific clients. 首先要解决的是如何将WS连接实例与特定客户端相关联。 The answer to this is to use a map/dictionary/plain ol' javascript object with some sort of unique client identifier as the key and the instance of the WS connection as the value. 答案是使用map / dictionary / plain ol的javascript对象,将某种独特的客户端标识符作为键,并将WS连接实例作为值。 Pseudo-code: 伪代码:

let connections = { 'client1': WSinstance, 'client2': WSinstance };

You would add to this object every time you create a new WS instance. 每次创建新的WS实例时,都将添加到该对象。 Assuming you have a way to uniquely identify a client and that is stored in the variable clientId , you could do the following: 假设您有一种唯一标识客户端的方法,并且该方法存储在变量clientId ,则可以执行以下操作:

io.on('connection', function (socket) {
  connections[clientId] = socket;
}

Now if you want to emit a message to just client1 you can use the WS instance associated with them by grabbing it from the object connections.client1 or if you want to target client2 connections.client2 现在,如果您只想向client1发送消息,则可以通过从对象connections.client1抓取它来使用与其关联的WS实例,或者如果您希望将client2 connections.client2作为目标

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从Node.js socket.io服务器向浏览器客户端发送二进制数据? - How to send binary data from a Node.js socket.io server to a browser client? 以gzip格式从node.js服务器向客户端发送socket.io响应数据 - Send socket.io response data to client from node.js server in gzip format 使用 socket.io 和 node.js 向特定客户端发送消息 - Send message to specific client with socket.io and node.js node.js socket.io无法发送到特定客户端 - node.js socket.io cannot send to specific client Send Message to Socket, 从C#客户端到node.js + socket.io服务器 - Send Message to Socket, from C# client to node.js + socket.io server 如何将二进制数据从Node.js socket.io(v2.0.x)服务器发送到浏览器客户端? - How to send binary data from a Node.js socket.io (v2.0.x) server to a browser client? 使用socket.io和node.js从服务器向客户端发送消息 - Send message to client from server using socket.io and node.js 从不带socket.io的node.js向客户端发送消息 - Send message to client from node.js without socket.io 当一个客户端连接到Node.js的Socket.io中时,如何向其他客户端发送数据? - How to send data to some other client when one client connects in Socket.io , Node js? 如何使用 socket.io 在客户端(网络浏览器)中显示来自 node.js 服务器的实时数据? - How to use socket.io to display realtime data in the client (web browser) from the node.js server?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM