简体   繁体   English

socket.io Web客户端不起作用

[英]socket.io web client not working

I recently met the socket world with socket.io and node.js I found this server example online: https://gist.github.com/creationix/707146 I created a first client on iOS and i receive and dispatch messages, the same as telnet client, next I would like to create a second client with socket.io to receive the messages on the browser too. 我最近在socket.io和node.js上遇到了套接字世界,我在网上找到了这个服务器示例: https : //gist.github.com/creationix/707146我在iOS上创建了第一个客户端,并且接收和发送消息,相同作为telnet客户端,接下来我想使用socket.io创建第二个客户端,以便也在浏览器上接收消息。

I tried the example in the howto: http://socket.io/#how-to-use but with these examples the client is not even recognized! 我在howto中尝试了该示例: http : //socket.io/#how-to-use,但是使用这些示例,甚至无法识别客户端!

Where am I wrong? 我哪里错了? Where do I start? 我从哪里开始?

The server code: 服务器代码:

// Load the TCP Library
net = require('net');

// Keep track of the chat clients
var clients = [];

// Start a TCP Server
net.createServer(function (socket) {

// Identify this client
socket.name = socket.remoteAddress + ":" + socket.remotePort 

// Put this new client in the list
clients.push(socket);

// Send a nice welcome message and announce
socket.write("Welcome " + socket.name + "\n");
broadcast(socket.name + " joined the chat\n", socket);

// Handle incoming messages from clients.
socket.on('data', function (data) {
broadcast(socket.name + "> " + data, socket);
});

// Remove the client from the list when it leaves
socket.on('end', function () {
clients.splice(clients.indexOf(socket), 1);
broadcast(socket.name + " left the chat.\n");
});

// Send a message to all clients
function broadcast(message, sender) {
clients.forEach(function (client) {
  // Don't want to send it to sender
  if (client === sender) return;
  client.write(message);
});
// Log it to the server output too
process.stdout.write(message)
}

}).listen(5000);

// Put a friendly message on the terminal of the server.
console.log("Chat server running at port 5000\n");

The client code: 客户端代码:

<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
 });
</script>

Thanks a lot. 非常感谢。

I know its late, and you probably solved the issue but the server is listening on port 5000. Your client is connecting to port 80. 我知道已经很晚了,您可能已经解决了该问题,但是服务器正在侦听端口5000。您的客户端正在连接到端口80。

Change the clinet code to: 将客户端代码更改为:

   <script src="/socket.io/socket.io.js"></script>
   <script>
   var socket = io.connect('http://localhost:5000');
   socket.on('news', function (data) {
   console.log(data);
   socket.emit('my other event', { my: 'data' });
    });
   </script>

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM