webSocket
首先安装node。
然后
npm install ws
ws是webSocket模块。
然后创建一个sever.js文件,在里面新建一个服务
var WebSocketServer = require('ws').Server, wss = new WebSocketServer({ port: 8181 }); wss.on('connection', function (ws) { console.log('client connected'); ws.on('message', function (message) { console.log(message); }); });
之后就是页面了,index.html,在页面中创建一个连接
var ws = new WebSocket("ws://localhost:8181"); ws.onopen = function (e) { console.log('Connection to server opened'); } function sendMessage() { ws.send($('#message').val()); }
使用send方法发送数据。
一个实时聊天的例子
1.安装node-uuid模块,用来给每个连接一个唯一号。
2.服务端消息发送
消息类型分notification和message两种,前者是提示信息,后者是聊天内容。消息还包含一个id、昵称和消息内容。在上一节有学习到readyState有四个值,OPEN表示连接建立可以发送消息。如果页面关闭了,为WebSocket.CLOSE。
function wsSend(type, client_uuid, nickname, message) { for (var i = 0; i < clients.length; i++) { var clientSocket = clients[i].ws; if (clientSocket.readyState === WebSocket.OPEN) { clientSocket.send(JSON.stringify({ "type": type, "id": client_uuid, "nickname": nickname, "message": message })); } } }
3.服务端处理连接
每新增加一个连接,都会发送一条匿名用户的加入的提示消息,如果消息中带有“/nick” 认为这一个修改昵称的消息。然后更新客户端的昵称。其他都会当做聊天消息处理。
wss.on('connection', function(ws) { var client_uuid = uuid.v4(); var nickname = "AnonymousUser" + clientIndex; clientIndex += 1; clients.push({ "id": client_uuid, "ws": ws, "nickname": nickname }); console.log('client [%s] connected', client_uuid); var connect_message = nickname + " has connected"; wsSend("notification", client_uuid, nickname, connect_message); console.log('client [%s] connected', client_uuid); ws.on('message', function(message) { if (message.indexOf('/nick') === 0) { var nickname_array = message.split(' '); if (nickname_array.length >= 2) { var old_nickname = nickname; nickname = nickname_array[1]; var nickname_message = "Client " + old_nickname + " changed to " + nickname; wsSend("nick_update", client_uuid, nickname, nickname_message); } } else { wsSend("message", client_uuid, nickname, message); } });
处理连接关闭:
var closeSocket = function(customMessage) { for (var i = 0; i < clients.length; i++) { if (clients[i].id == client_uuid) { var disconnect_message; if (customMessage) { disconnect_message = customMessage; } else { disconnect_message = nickname + " has disconnected"; } wsSend("notification", client_uuid, nickname, disconnect_message); clients.splice(i, 1); } } }; ws.on('close', function () { closeSocket(); });
4.客户端
没有启动时,页面如下,change按钮用来修改昵称。
js:
//建立连接 var ws = new WebSocket("ws://localhost:8181"); var nickname = ""; ws.onopen = function (e) { console.log('Connection to server opened'); } //显示 function appendLog(type, nickname, message) { if (typeof message == "undefined") return; var messages = document.getElementById('messages'); var messageElem = document.createElement("li"); var preface_label; if (type === 'notification') { preface_label = "<span class=\"label label-info\">*</span>"; } else if (type == 'nick_update') { preface_label = "<span class=\"label label-warning\">*</span>"; } else { preface_label = "<span class=\"label label-success\">" + nickname + "</span>"; } var message_text = "<h2>" + preface_label + " " + message + "</h2>"; messageElem.innerHTML = message_text; messages.appendChild(messageElem); } //收到消息处理 ws.onmessage = function (e) { var data = JSON.parse(e.data); nickname = data.nickname; appendLog(data.type, data.nickname, data.message); console.log("ID: [%s] = %s", data.id, data.message); } ws.onclose = function (e) { appendLog("Connection closed"); console.log("Connection closed"); } //发送消息 function sendMessage() { var messageField = document.getElementById('message'); if (ws.readyState === WebSocket.OPEN) { ws.send(messageField.value); } messageField.value = ''; messageField.focus(); } //修改名称 function changName() { var name = $("#name").val(); if (ws.readyState === WebSocket.OPEN) { ws.send("/nick " + name); } }
源码:http://pan.baidu.com/s/1c2FfKbA
源码:http://pan.baidu.com/s/1o8KRmUQ 加入了socket.io的实现。
API:WebSocket API
其实我想叫洛羽的,谁抢了我的昵称!!