无法开始使用NodeJS和SocketIO
我正在尝试使用socket.io和node.js来实现基本结构,同时使用('net')
实现在node.js的主页上显示的tcpfunction来创build服务器。
由于没有太多的代码,这是我迄今为止
服务器:
// Setup the server var tcpProtocol = require('net'); var serverListener = tcpProtocol.createServer(tcpHandler); var socketIO = require('socket.io').listen(serverListener); function tcpHandler(socket) { console.log("TCP Handler received a call."); socket.pipe(socket); } socketIO.sockets.on('connection', function(socket) { console.log("Connection maid."); }); socketIO.sockets.on('login', function(username, password) { console.log("login called."); console.log('username: ' + username); console.log('password: ' + password); }); serverListener.listen(5055, '127.0.0.1'); console.log("Server started on port 5055");
当然,客户:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Test Client</title> <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> <script src="https://cdn.socket.io/socket.io-1.2.1.js"></script> </head> <body> <script> var socket = io.connect('http://localhost:5055'); $(function() { socket.emit('login', 'Chris', 'PassBob'); console.log("sent"); }); </script> </body> </html>
服务器正在打印tcpHandler的调用,但是socketIO调用没有得到任何识别。 从客户端sent
打印,但我注意到tcpHandler
调用被重复调用几次,就像它仍然试图发送失败后的数据或东西? 只是一个假设。
你应该在connection
事件中处理你的套接字逻辑。
你的代码应该是这样的:
服务器
socketIO.sockets.on('connection', function(socket) { console.log("Connection maid."); socket.on('login', function(username, password) { console.log("login called."); console.log('username: ' + username); console.log('password: ' + password); }); });
你可以参考这个开源项目 – 里面有很多套接字逻辑(突出显示)
https://github.com/thecatontheflat/agile-estimation/blob/0.0.3/server.js#L94-L196
即使代码很脏,我相信你可以从那里得到很多有用的例子