【问题标题】:socket.io web client not workingsocket.io 网络客户端不工作
【发布时间】:2013-05-07 21:29:15
【问题描述】:

我最近遇到了 socket.io 和 node.js 的套接字世界 我在网上找到了这个服务器示例:https://gist.github.com/creationix/707146 我在 iOS 上创建了第一个客户端,我接收和发送消息,与 telnet 客户端相同,接下来我想使用 socket.io 创建第二个客户端,以便在浏览器上接收消息。

我尝试了操作指南中的示例:http://socket.io/#how-to-use,但这些示例甚至无法识别客户端!

我哪里错了?我从哪里开始?

服务器代码:

// 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");

客户端代码:

<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>

非常感谢。

【问题讨论】:

  • 请贴出您使用的实际代码,否则我们无法帮助您!
  • 你所指的要点与socket.io无关;在 gist 中使用 TCP 套接字服务器上的socket.io 客户端是行不通的。
  • 有没有办法创建网络客户端?
  • 从 Socket.IO 基础开始(来自socket.io)。了解如何创建一个简单的服务器和客户端。从那里你会发现让它全部启动并运行起来并不难。 :)

标签: javascript jquery node.js socket.io


【解决方案1】:

我知道它已经晚了,你可能已经解决了这个问题,但服务器正在侦听端口 5000。 您的客户端正在连接到端口 80。

将客户端代码更改为:

   <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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 2019-02-15
    • 2017-08-17
    • 1970-01-01
    • 2012-02-20
    相关资源
    最近更新 更多