socket
socket
通信流程
一个简单的socket聊天
SocketServer.js
1 var net = require('net') 2 3 var chatServer = net.createServer() 4 5 //chat对象集合 6 var clientMap = new Object() 7 8 var i = 0 9 10 //创建一个连接 11 chatServer.on('connection',function(client){ 12 console.log('客户端有人连接') 13 14 //用自然数记录用户的名字 15 client.name = ++i 16 17 //记录client对象 18 clientMap[client.name] 19 }) 20 21 //监听端口 22 chatServer.listen(9000)
ClientSocket.js
1 var net = require('net') 2 3 //声明客户端socket 4 var client = new net.Socket() 5 6 client.setEncoding = 'UTF-8' 7 8 //连接服务器 9 client.connect(9000,'127.0.0.1',function(){ 10 client.write('您好') 11 })