gpt4 book ai didi

javascript - NodeJS + 套接字.io : simple Client/Server example not working

转载 作者:数据小太阳 更新时间:2023-10-29 04:39:18 26 4
gpt4 key购买 nike

我正在使用 NodeJS v0.4.8 和最新版本的 socket.io

npm install socket.io

在 Ubuntu 上:

Linux mars 2.6.38-8-generic #42-Ubuntu SMP Mon Apr 11 03:31:50 UTC 2011 i686 i686 i386 GNU/Linux

不幸的是,以下代码不会产生任何输出,无论是在客户端还是在服务器端。

有人知道吗?

服务器端

var http = require('http'),  
io = require('socket.io'),
fs = require('fs'),
sys = require('sys');

respcont = fs.readFileSync('testclient.js');

server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(respcont);
});
server.listen(8082);

var socket = io.listen(server);
socket.on('connection', function(client){

sys.puts("New client is here!");
client.send("hello world");

client.on('message', function(msg) { sys.puts("client has sent:"+msg); }) ;
client.on('disconnect', function() { sys.puts("Client has disconnected"); }) ;
});

客户端

<html>
<body>
<script type="text/javascript" src="http://localhost:8082/socket.io/socket.io.js"></script>
<script>
var socket = new io.Socket(null,{port:8082,rememberTransport:true,timeout:1500});
socket.connect();
socket.on('connect', function() {
console.log('connected to server');
socket.send('Hi Server...');
});

socket.on('message', function() {
console.log('received a message!');
});

socket.on('disconnect', function() {
console.log('disconnected from server');
});

</script>
</body>
</html>

NodeJS 的输出(不是 sys.puts("...") 调用)是:

info - socket.io started debug - served static /socket.io.js debug - client authorized info - handshake authorized info - handshaken b61a5c2751c1c8c8493db4b79d19e779

最佳答案

Express 3.0 + Socket.io 工作示例

服务器(app.js)

var express = require('express');
var app = express.createServer();
var socket = require('socket.io');
app.configure(function(){
app.use(express.static(__dirname + '/'));
});
var server = app.listen(8081);
var io = socket.listen(server);
io.sockets.on('connection', function (socket) {
console.log("connnect");
socket.on('disconnect', function (socket) {
console.log("disconnect");
});
});

客户端(index.html)

<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8081');
</script>

您可以使用下面的链接 fork 代码 https://github.com/sreekumar-kr/Expree3.0---Socket.IO

关于javascript - NodeJS + 套接字.io : simple Client/Server example not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6411070/

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