gpt4 book ai didi

node.js - Socket.io 服务器发出不触发

转载 作者:搜寻专家 更新时间:2023-10-31 23:44:04 25 4
gpt4 key购买 nike

好的,尝试使用 NodeJS 和 socket.io 时遇到了问题。我在本地主机上安装并运行了 NodeJS 和 Socket.io。目前我有以下设置:

server.js

// Require HTTP module (to start server) and Socket.IO
var http = require('http'), io = require('socket.io');

// Start the server at port 8080
var server = http.createServer(function(req, res){

// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>NodeJS Server Online</h1>');
});
server.listen(8080);

// Create a Socket.IO instance, passing it our server
var socketserver = io.listen(server);

// Add a connect listener
socketserver.on('connection', function(socket){

socket.emit("server ready");

socket.on('test', function (msg) {
socket.broadcast.emit('TEST:', msg);
console.log(msg);
});

socket.on('user message', function (msg) {
socket.broadcast.emit('user message', msg);
console.log(msg);
});

});

client.js

$(document).ready(function() {
// Stuff to do as soon as the DOM is ready;
var socket = io.connect('http://localhost',{port:8080});

socket.on('server ready',function() {
messages.append("<li>Server Ready...</li>");
console.log("Server Ready");
});

// Add a connect listener
socket.on('connect',function() {
messages.append("<li>Connected...</li>");
console.log("connected");
socket.emit('test',"Just testing");
});

});

服务器启动正常,但我的问题是 server.js 没有触发 socket.emit("server ready"); 行。客户端代码在 terminal.app 中工作正常,测试我的服务器输出这一行:

websocket received data packet 5:::{"name":"test","args":["Just testing"]}

我错过了什么?为什么服务器端没有触发?

最佳答案

我将 socket.io 更新为 0.7.2,然后稍微修改了您的示例以使用 express。下面的代码能够接收到“服务器就绪”事件。

Node 服务器:

var http = require('http'),  
express = require('express');

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
app.use(express.static(__dirname + '/public'));
});

app.listen(9000);
console.log("server started");

// socket.io
var io = require('socket.io').listen(app);

io.sockets.on('connection', function(socket){
socket.emit('server ready', {msg: 'hi'}) ;
});

网页(/sock.html):

<html>
<body>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('server ready', function(data){ console.log('server ready!'); }) ;
</script>
</body>
</html>

关于node.js - Socket.io 服务器发出不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6483862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com