node搭建http服务区和webSocket服务器 //?加载http核心模块 var?http?=?require(‘http’)//创建web服务器var?server?=?http.createServer()/*???提供数据服务,注册request请求事件,当客户端请求,自动执行回调函数????request?请求对象,获取客户端的一些请求信息????response?响应对象,给客户端发送响应消息*/server.on(‘request’,?function?(request,?response)?{??//response使用Write来向客户端发送数据,但是一定要用end来结束响应数据??if?(request.url?==?‘/’)?{????response.write(‘hello’)????response.end()????//可以写成response.end(‘hello’)??}??else?if?(request.url?==?‘/login’)?{????response.write(‘login’)????response.end()????//可以直接写成response.end(‘login’)??}})//绑定端口号启动服务器server.listen(3000,?function?()?{??console.log(‘服务器启动成功,可以通过"http://127.0.0.1:3000/"来进行访问’);});const?WebSocket?=?require(‘ws’)//?const?ws?=?new?WebSocket(?options?)?//options就是一个对象const?ws?=?new?WebSocket.Server({??port:?5000,??host:?‘localhost’})//?console.log(ws)var?clients?=?{};var?count?=?0;ws.on(‘connection’,?client?=>?{??client.name?=?++count;//对客户端进行编号??clients[client.name]?=?client;//将连接到客户端存到集合内??//3.接收客户端发来的数据??client.on(‘message’,?msg?=>?{????console.log(客户端${client.name}:${msg}} )????boardcast(client,?msg);//接收到客户信息时,调用函数显示所有信息??});??//4.监听客户端下线??client.on(‘close’,?()?=>?{????delete?clients[client.name];//清除下线客户端????console.log(客户端${client.name}closed~~~ )??});??//对客户端发来数据进行封装调用??function?boardcast(client,?msg)?{????for?(var?key?in?clients)?{??????clients[key].send(msg);//接收到客户端信息,便利客户端,显示所有信息????}??}})
|