消息类型分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按钮用来修改昵称。
<div> <div> <ul></ul> <hr/> <form role="form" onsubmit="sendMessage(); return false;"> <div> <input type="text" placeholder="Type text to echo in here" value="" autofocus/> </div> <button type="button"> Send Message </button> </form> <div><span>nikename:</span><input type="text" /> <button>change</button></div> </div> </div>
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); } }
运行结果:
页面关闭之后,连接马上断开。
这种实时响应的体验简直不能太爽,代码也清爽了,前端体验也更好,客户端不用一直发请求,服务端不用等着被轮询。
小结:上面例子的代码都很好理解,接下来学习WebSocket协议。