链接过程

前端

1、CREATED WEBSOCKE

2、ONOPEN

3、ONMESSAGE

服务端

1、收到request

2、给客户端发送消息,生成id

  1. //msg
  2. {
  3. type: "id",
  4. id: Date.now()
  5. }

前端

1、收到messge,type为id,

2、给服务端发送消息type=username的消息,携带id

  1. // clientID = msg.id
  2. var msg = {
  3. name: document.getElementById("name").value,
  4. date: Date.now(),
  5. id: clientID,
  6. type: "username"
  7. };

服务端

1、收到type为username的msg

2、设置connect.username = msg.name;

3、广播给其他用户消息 type: "userlist",


  1. var userListMsg = {
  2. type: "userlist",
  3. users: []
  4. };

4、服务端发送usename消息

  1. if (sendToClients) {
  2. var msgString = JSON.stringify(msg);
  3. var i;
  4. for (i=0; i<connectionArray.length; i++) {
  5. console.log(102, msgString);
  6. connectionArray[i].sendUTF(msgString);
  7. }
  8. }

前端

1、 前端收到type=userlist的message,渲染用户列表 2、 前端收到type=username的message,渲染聊天室的登录消息

  1. User lili signed in at 上午10:03:24
  2. User hanmei signed in at 上午10:03:24
  1. /**
  2. * @Description: In User Settings Edit
  3. * @Author: your name
  4. * @Date: 2019-09-02 16:17:14
  5. * @LastEditTime: 2019-09-04 10:16:54
  6. * @LastEditors: Please set LastEditors
  7. */
  8.  
  9. "use strict";
  10.  
  11. var https = require('http');
  12. // var fs = require('fs');
  13. var WebSocketServer = require('websocket').server;
  14.  
  15. var connectionArray = [];
  16. var nextID = Date.now();
  17. var appendToMakeUnique = 1;
  18.  
  19. // var httpsOptions = {
  20. // key: fs.readFileSync("/etc/pki/tls/private/mdn-samples.mozilla.org.key"),
  21. // cert: fs.readFileSync("/etc/pki/tls/certs/mdn-samples.mozilla.org.crt")
  22. // };
  23.  
  24. /**
  25. * @description 创建http server
  26. *
  27. */
  28. var httpsServer = https.createServer(function(request, response) {
  29. console.log((new Date()) + " Received request for " + request.url);
  30. response.writeHead(404);
  31. response.end();
  32. });
  33.  
  34. httpsServer.listen(6502, function() {
  35. console.log((new Date()) + " Server is listening on port 6502");
  36. });
  37.  
  38. console.log("***CREATING WEBSOCKET SERVER");
  39.  
  40. /**
  41. *@description 创建WebSocketServer
  42. *
  43. */
  44. var wsServer = new WebSocketServer({
  45. httpServer: httpsServer,
  46. autoAcceptConnections: false
  47. });
  48. console.log("***CREATED");
  49.  
  50. function originIsAllowed(origin) {
  51. // This is where you put code to ensure the connection should
  52. // be accepted. Return false if it shouldn't be.
  53. return true;
  54. }
  55.  
  56. function isUsernameUnique(name) {
  57. var isUnique = true;
  58. var i;
  59.  
  60. for (i=0; i<connectionArray.length; i++) {
  61. if (connectionArray[i].username === name) {
  62. isUnique = false;
  63. break;
  64. }
  65. }
  66. return isUnique;
  67. }
  68.  
  69. function getConnectionForID(id) {
  70. var connect = null;
  71. var i;
  72.  
  73. for (i=0; i<connectionArray.length; i++) {
  74. if (connectionArray[i].clientID === id) {
  75. connect = connectionArray[i];
  76. break;
  77. }
  78. }
  79.  
  80. return connect;
  81. }
  82.  
  83. function makeUserListMessage() {
  84. var userListMsg = {
  85. type: "userlist",
  86. users: []
  87. };
  88. var i;
  89.  
  90. // Add the users to the list
  91.  
  92. for (i=0; i<connectionArray.length; i++) {
  93. userListMsg.users.push(connectionArray[i].username);
  94. }
  95.  
  96. return userListMsg;
  97. }
  98.  
  99. function sendUserListToAll() {
  100. var userListMsg = makeUserListMessage();
  101. // console.log(111, userListMsg);
  102.  
  103. var userListMsgStr = JSON.stringify(userListMsg);
  104. var i;
  105. // console.log(connectionArray);
  106.  
  107. for (i=0; i<connectionArray.length; i++) {
  108. //立即将指定的字符串作为UTF-8 WebSocket消息发送给远程对等体
  109. console.log(100, userListMsgStr);
  110.  
  111. connectionArray[i].sendUTF(userListMsgStr);
  112. }
  113. }
  114.  
  115. console.log("***CRETING REQUEST HANDLER");
  116.  
  117. wsServer.on('request', function(request) {
  118. console.log("Handling request from " + request.origin);
  119. if (!originIsAllowed(request.origin)) {
  120. request.reject();
  121. console.log("Connection from " + request.origin + " rejected.");
  122. return;
  123. }
  124.  
  125. // Accept the request and get a connection.
  126.  
  127. var connection = request.accept("json", request.origin);
  128.  
  129. // Add the new connection to our list of connections.
  130.  
  131. console.log((new Date()) + " Connection accepted.");
  132. connectionArray.push(connection);
  133. // console.log(connectionArray);
  134.  
  135. // Send the new client its token; it will
  136. // respond with its login username.
  137.  
  138. connection.clientID = nextID;
  139. // console.log(connection.clientID);
  140.  
  141. nextID++;
  142.  
  143. var msg = {
  144. type: "id",
  145. id: connection.clientID
  146. };
  147. console.log(99, msg);
  148.  
  149. connection.sendUTF(JSON.stringify(msg));
  150.  
  151. /**
  152. * @description 接收消息
  153. */
  154.  
  155. connection.on('message', function(message) {
  156. console.log("***Received MESSAGE*******", message);
  157. if (message.type === 'utf8') {
  158. // console.log("Received Message: " + message.utf8Data);ß
  159.  
  160. // Process messages
  161.  
  162. var sendToClients = true;
  163. msg = JSON.parse(message.utf8Data);
  164. // console.log(1111,msg);
  165.  
  166. var connect = getConnectionForID(msg.id);
  167.  
  168. /**
  169. * @description 接收到的数据
  170. */
  171.  
  172. switch(msg.type) {
  173. // Public text message in the chat room
  174. case "message":
  175. msg.name = connect.username;
  176. msg.text = msg.text.replace(/(<([^>]+)>)/ig,"");
  177. break;
  178. /**
  179. * @description 登录的操作,通知其他人展示
  180. */
  181. // Username change request
  182. case "username":
  183. var nameChanged = false;
  184. var origName = msg.name;
  185. while (!isUsernameUnique(msg.name)) {
  186. msg.name = origName + appendToMakeUnique;
  187. appendToMakeUnique++;
  188. nameChanged = true;
  189. }
  190. if (nameChanged) {
  191. var changeMsg = {
  192. id: msg.id,
  193. type: "rejectusername",
  194. name: msg.name
  195. };
  196. console.log(101,changeMsg);
  197.  
  198. connect.sendUTF(JSON.stringify(changeMsg));
  199. }
  200. connect.username = msg.name;
  201. sendUserListToAll();
  202. break;
  203. }
  204.  
  205. // Convert the message back to JSON and send it out
  206. // to all clients.
  207. /**
  208. * @desciption 发送给客户端消息
  209. */
  210. if (sendToClients) {
  211. var msgString = JSON.stringify(msg);
  212. var i;
  213.  
  214. for (i=0; i<connectionArray.length; i++) {
  215. console.log(102, msgString);
  216.  
  217. connectionArray[i].sendUTF(msgString);
  218. }
  219. }
  220. }
  221. });
  222.  
  223. // Handle the WebSocket "close" event; this means a user has logged off
  224. // or has been disconnected.
  225. /**
  226. * @description 关闭socket
  227. */
  228. connection.on('close', function(connection) {
  229. // console.log(connectionArray);
  230. console.log(JSON.stringify(connection));
  231. console.log((new Date()) + " Peer " + connection.remoteAddress + " disconnected.");
  232.  
  233. connectionArray = connectionArray.filter(function(el, idx, ar) {
  234. // console.log(el.connected);
  235.  
  236. return el.connected;
  237. });
  238. sendUserListToAll(); // Update the user lists
  239. // console.log(connectionArray);
  240.  
  241. });
  242.  
  243. });
  244.  
  245. console.log("***REQUEST HANDLER CREATED");

  

参考文章

websocket 服务搭建的更多相关文章

  1. nodejs搭建简单的websocket服务端

    创建websocket服务端使用了nodejs-websocket ,首先要安装nodejs-websocket,在项目的目录下: npm install nodejs-websocket 1.搭建w ...

  2. Netty 搭建 WebSocket 服务端

    一.编码器.解码器 ... ... @Autowired private HttpRequestHandler httpRequestHandler; @Autowired private TextW ...

  3. JumpServer1.0 服务搭建

    JumpServer1.0 服务搭建 系统环境配置 setenforce 0 systemctl stop iptables.service systemctl stop firewalld.serv ...

  4. asp.net网站作为websocket服务端的应用该如何写

    最近被websocket的一个问题困扰了很久,有一个需求是在web网站中搭建websocket服务.客户端通过网页与服务器建立连接,然后服务器根据ip给客户端网页发送信息. 其实,这个需求并不难,只是 ...

  5. springboot+kurento+coturn+contos的视频通讯服务搭建

    springboot+kurento+coturn+contos的视频通讯服务搭建 服务器CentOS Linux release 7.9.2009 (Core) 本案例成功于20210628 1.默 ...

  6. 【Java分享客栈】SpringBoot整合WebSocket+Stomp搭建群聊项目

    前言 前两周经常有大学生小伙伴私信给我,问我可否有偿提供毕设帮助,我说暂时没有这个打算,因为工作实在太忙,现阶段无法投入到这样的领域内,其中有两个小伙伴又问到我websocket该怎么使用,想给自己的 ...

  7. C# WebSocket 服务端示例代码 + HTML5客户端示例代码

    WebSocket服务端 C#示例代码 using System; using System.Collections.Generic; using System.Linq; using System. ...

  8. ServiceStack.Hello——跨平台.net REST api服务搭建

    ServiceStack.Hello--跨平台.net REST api服务搭建 自己创建: https://github.com/ServiceStack/ServiceStack/wiki/Cre ...

  9. WCFRESTFul服务搭建及实现增删改查

    WCFRESTFul服务搭建及实现增删改查 RESTful Wcf是一种基于Http协议的服务架构风格,  RESTful 的服务通常是架构层面上的考虑. 因为它天生就具有很好的跨平台跨语言的集成能力 ...

随机推荐

  1. React(7) --react父子组件传参

    react父子组件传参 父级向子级传参:在父组件中,我们引入子组件,通过给子组件添加属性,来起到传参的作用,子组件可以通过props获取父组件传过来的参数. 在父组件中: import React f ...

  2. python数字图像处理(三)边缘检测常用算子

    在该文将介绍基本的几种应用于边缘检测的滤波器,首先我们读入saber用来做为示例的图像 #读入图像代码,在此之前应当引入必要的opencv matplotlib numpy saber = cv2.i ...

  3. hdu1214 圆桌会议

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1214 HDU ACM集训队的队员在暑假集训时经常要讨论自己在做题中遇到的问题.每当面临自己解决不了的问 ...

  4. html5 图片墙

    代码实例: <!DOCTYPE html> <html> <head> <style> body,html{ padding:0;margin:0;wi ...

  5. AGC003[BCDEF]题解

    2018-12-28 有点累EF明天再写叭=v= 2018-12-29 update EF B - Simplified mahjong 可以注意到 一段连续的非0序列都可以凑出 就是显然%2=0的可 ...

  6. 计蒜客NOIP模拟D1T2

    原题: 蒜头君有一棵有根树,树的每一边都有边权,蒜头君想知道任意两点间最短距离之和为多少.另外,由于各种原因,蒜头君的树的边的边权会发生若干次改变,蒜头君想让你告诉他,每一次改变后,任意两点间最短距离 ...

  7. js 中HTML的 onkeycode 和onkeydown属性事件

    <!DOCTYPE html><html><head><script>function displayResult(){var x=document.g ...

  8. 【leetcode】416. Partition Equal Subset Sum

    题目如下: 解题思路:对于这种判断是否的题目,首先看看动态规划能不能解决.本题可以看成是从nums中任选i个元素,判断其和是否为sum(nums)/2,很显然从nums中任选i个元素的和的取值范围是[ ...

  9. 【CF741D】Arpa’s letter-marked tree and Mehrdad’s Dokhtar-kosh paths(dsu on tree)

    题意:我们称一个字符串为周驿东串当且仅当重排它的字符可以组成一个回文串. 给出一个n个点的有根树,根为1,每条边上有一个从a到v的字符,求每个点的子树中所有简单路径可以组成的周驿东串中的最长长度. n ...

  10. 记录从现在开始,我的第一篇blog

    最近在读刘未鹏的<暗时间>,深受作者的启发,决定开始书写blog. 书写是为了更好的思考,希望自己能持之以恒的坚持做这件事情. 这本书很推荐给所有同学,不仅关于时间管理,执行力,心理学, ...