一、安装NodeJS
官网下载,下载好后一路下一步
https://nodejs.org/en/
二、配置环境
1、新建一个node文件夹
2、新建一个JSON文件,名字为package.json,内容为
{ "name": "socket", "version": "0.0.1", "description": "myproject", "dependencies": {}, "devDependencies": {} }
3、在node文件夹目录下打开cmd,安装两个组件net、ws
npm install net --save-dev npm install ws --save-dev
4、新建一个SocketClient.js文件,内容为
var net = require('net'); var client = net.connect('9001','192.168.1.106',function(){ console.log('已经与服务器连接'); client.write('hello server'); }); client.on('data',function(data){ console.log(data.toString()); //client.end(); }); client.on('end',function(){ console.log('服务端断开'); });
5、新建一个SocketServer.js文件,内容为
var net = require('net'); var chatServer = net.createServer(), clientList = []; clientMap = new Object(); var ii = 0; chatServer.on('connection', function(client) { client.name = ++ii; clientMap[client.name] = client; //数据接收事件 client.write('Hi client'); client.on('data', function(data) { console.log('客户端传来:' + data); //client.write(data); broadcast(data, client);// 转发来自客户端的信息 }); //数据错误事件 client.on('error',function(exception){ console.log('client error:' + exception); client.end(); }); //客户端关闭事件 client.on('close',function(data){ delete clientMap[client.name]; console.log(client.name +'下线了'); broadcast(client.name +'下线了',client); }); }); function broadcast(message, client) { for(var key in clientMap){ clientMap[key].write(client.name + 'say:' + message + '\n'); } }; chatServer.listen(9001, function(){ var address = chatServer.address(); console.log('服务已监听: %j', address); });
6、新建一个WsServer.js文件,内容为:
var WebSocketServer = require('ws').Server; var wss = new WebSocketServer({port: 9000}); var i = 0; //var wsObj = {}; wss.on('connection', function(ws) { ws.name = ++i; //wsObj[ws.name] = ws; console.log(ws.name + '上线'); ws.on('message', function(message) { ws.send(message); console.log('received: '+ ws.name +'%j', message); }); ws.send(ws.name + ', welcome'); ws.on('close', function(){ //global.gc(); //调用内存回收 console.log(ws.name + ', leave'); }); });