websocket 服务搭建
链接过程
前端
1、CREATED WEBSOCKE
2、ONOPEN
3、ONMESSAGE
服务端
1、收到request
2、给客户端发送消息,生成id
//msg
{
type: "id",
id: Date.now()
}
前端
1、收到messge,type为id,
2、给服务端发送消息type=username的消息,携带id
// clientID = msg.id
var msg = {
name: document.getElementById("name").value,
date: Date.now(),
id: clientID,
type: "username"
};
服务端
1、收到type为username的msg
2、设置connect.username = msg.name;
3、广播给其他用户消息 type: "userlist",
var userListMsg = {
type: "userlist",
users: []
};
4、服务端发送usename消息
if (sendToClients) {
var msgString = JSON.stringify(msg);
var i;
for (i=0; i<connectionArray.length; i++) {
console.log(102, msgString);
connectionArray[i].sendUTF(msgString);
}
}
前端
1、 前端收到type=userlist的message,渲染用户列表 2、 前端收到type=username的message,渲染聊天室的登录消息
User lili signed in at 上午10:03:24
User hanmei signed in at 上午10:03:24
- /**
- * @Description: In User Settings Edit
- * @Author: your name
- * @Date: 2019-09-02 16:17:14
- * @LastEditTime: 2019-09-04 10:16:54
- * @LastEditors: Please set LastEditors
- */
- "use strict";
- var https = require('http');
- // var fs = require('fs');
- var WebSocketServer = require('websocket').server;
- var connectionArray = [];
- var nextID = Date.now();
- var appendToMakeUnique = 1;
- // var httpsOptions = {
- // key: fs.readFileSync("/etc/pki/tls/private/mdn-samples.mozilla.org.key"),
- // cert: fs.readFileSync("/etc/pki/tls/certs/mdn-samples.mozilla.org.crt")
- // };
- /**
- * @description 创建http server
- *
- */
- var httpsServer = https.createServer(function(request, response) {
- console.log((new Date()) + " Received request for " + request.url);
- response.writeHead(404);
- response.end();
- });
- httpsServer.listen(6502, function() {
- console.log((new Date()) + " Server is listening on port 6502");
- });
- console.log("***CREATING WEBSOCKET SERVER");
- /**
- *@description 创建WebSocketServer
- *
- */
- var wsServer = new WebSocketServer({
- httpServer: httpsServer,
- autoAcceptConnections: false
- });
- console.log("***CREATED");
- function originIsAllowed(origin) {
- // This is where you put code to ensure the connection should
- // be accepted. Return false if it shouldn't be.
- return true;
- }
- function isUsernameUnique(name) {
- var isUnique = true;
- var i;
- for (i=0; i<connectionArray.length; i++) {
- if (connectionArray[i].username === name) {
- isUnique = false;
- break;
- }
- }
- return isUnique;
- }
- function getConnectionForID(id) {
- var connect = null;
- var i;
- for (i=0; i<connectionArray.length; i++) {
- if (connectionArray[i].clientID === id) {
- connect = connectionArray[i];
- break;
- }
- }
- return connect;
- }
- function makeUserListMessage() {
- var userListMsg = {
- type: "userlist",
- users: []
- };
- var i;
- // Add the users to the list
- for (i=0; i<connectionArray.length; i++) {
- userListMsg.users.push(connectionArray[i].username);
- }
- return userListMsg;
- }
- function sendUserListToAll() {
- var userListMsg = makeUserListMessage();
- // console.log(111, userListMsg);
- var userListMsgStr = JSON.stringify(userListMsg);
- var i;
- // console.log(connectionArray);
- for (i=0; i<connectionArray.length; i++) {
- //立即将指定的字符串作为UTF-8 WebSocket消息发送给远程对等体
- console.log(100, userListMsgStr);
- connectionArray[i].sendUTF(userListMsgStr);
- }
- }
- console.log("***CRETING REQUEST HANDLER");
- wsServer.on('request', function(request) {
- console.log("Handling request from " + request.origin);
- if (!originIsAllowed(request.origin)) {
- request.reject();
- console.log("Connection from " + request.origin + " rejected.");
- return;
- }
- // Accept the request and get a connection.
- var connection = request.accept("json", request.origin);
- // Add the new connection to our list of connections.
- console.log((new Date()) + " Connection accepted.");
- connectionArray.push(connection);
- // console.log(connectionArray);
- // Send the new client its token; it will
- // respond with its login username.
- connection.clientID = nextID;
- // console.log(connection.clientID);
- nextID++;
- var msg = {
- type: "id",
- id: connection.clientID
- };
- console.log(99, msg);
- connection.sendUTF(JSON.stringify(msg));
- /**
- * @description 接收消息
- */
- connection.on('message', function(message) {
- console.log("***Received MESSAGE*******", message);
- if (message.type === 'utf8') {
- // console.log("Received Message: " + message.utf8Data);ß
- // Process messages
- var sendToClients = true;
- msg = JSON.parse(message.utf8Data);
- // console.log(1111,msg);
- var connect = getConnectionForID(msg.id);
- /**
- * @description 接收到的数据
- */
- switch(msg.type) {
- // Public text message in the chat room
- case "message":
- msg.name = connect.username;
- msg.text = msg.text.replace(/(<([^>]+)>)/ig,"");
- break;
- /**
- * @description 登录的操作,通知其他人展示
- */
- // Username change request
- case "username":
- var nameChanged = false;
- var origName = msg.name;
- while (!isUsernameUnique(msg.name)) {
- msg.name = origName + appendToMakeUnique;
- appendToMakeUnique++;
- nameChanged = true;
- }
- if (nameChanged) {
- var changeMsg = {
- id: msg.id,
- type: "rejectusername",
- name: msg.name
- };
- console.log(101,changeMsg);
- connect.sendUTF(JSON.stringify(changeMsg));
- }
- connect.username = msg.name;
- sendUserListToAll();
- break;
- }
- // Convert the message back to JSON and send it out
- // to all clients.
- /**
- * @desciption 发送给客户端消息
- */
- if (sendToClients) {
- var msgString = JSON.stringify(msg);
- var i;
- for (i=0; i<connectionArray.length; i++) {
- console.log(102, msgString);
- connectionArray[i].sendUTF(msgString);
- }
- }
- }
- });
- // Handle the WebSocket "close" event; this means a user has logged off
- // or has been disconnected.
- /**
- * @description 关闭socket
- */
- connection.on('close', function(connection) {
- // console.log(connectionArray);
- console.log(JSON.stringify(connection));
- console.log((new Date()) + " Peer " + connection.remoteAddress + " disconnected.");
- connectionArray = connectionArray.filter(function(el, idx, ar) {
- // console.log(el.connected);
- return el.connected;
- });
- sendUserListToAll(); // Update the user lists
- // console.log(connectionArray);
- });
- });
- console.log("***REQUEST HANDLER CREATED");
参考文章
websocket 服务搭建的更多相关文章
- nodejs搭建简单的websocket服务端
创建websocket服务端使用了nodejs-websocket ,首先要安装nodejs-websocket,在项目的目录下: npm install nodejs-websocket 1.搭建w ...
- Netty 搭建 WebSocket 服务端
一.编码器.解码器 ... ... @Autowired private HttpRequestHandler httpRequestHandler; @Autowired private TextW ...
- JumpServer1.0 服务搭建
JumpServer1.0 服务搭建 系统环境配置 setenforce 0 systemctl stop iptables.service systemctl stop firewalld.serv ...
- asp.net网站作为websocket服务端的应用该如何写
最近被websocket的一个问题困扰了很久,有一个需求是在web网站中搭建websocket服务.客户端通过网页与服务器建立连接,然后服务器根据ip给客户端网页发送信息. 其实,这个需求并不难,只是 ...
- springboot+kurento+coturn+contos的视频通讯服务搭建
springboot+kurento+coturn+contos的视频通讯服务搭建 服务器CentOS Linux release 7.9.2009 (Core) 本案例成功于20210628 1.默 ...
- 【Java分享客栈】SpringBoot整合WebSocket+Stomp搭建群聊项目
前言 前两周经常有大学生小伙伴私信给我,问我可否有偿提供毕设帮助,我说暂时没有这个打算,因为工作实在太忙,现阶段无法投入到这样的领域内,其中有两个小伙伴又问到我websocket该怎么使用,想给自己的 ...
- C# WebSocket 服务端示例代码 + HTML5客户端示例代码
WebSocket服务端 C#示例代码 using System; using System.Collections.Generic; using System.Linq; using System. ...
- ServiceStack.Hello——跨平台.net REST api服务搭建
ServiceStack.Hello--跨平台.net REST api服务搭建 自己创建: https://github.com/ServiceStack/ServiceStack/wiki/Cre ...
- WCFRESTFul服务搭建及实现增删改查
WCFRESTFul服务搭建及实现增删改查 RESTful Wcf是一种基于Http协议的服务架构风格, RESTful 的服务通常是架构层面上的考虑. 因为它天生就具有很好的跨平台跨语言的集成能力 ...
随机推荐
- React(7) --react父子组件传参
react父子组件传参 父级向子级传参:在父组件中,我们引入子组件,通过给子组件添加属性,来起到传参的作用,子组件可以通过props获取父组件传过来的参数. 在父组件中: import React f ...
- python数字图像处理(三)边缘检测常用算子
在该文将介绍基本的几种应用于边缘检测的滤波器,首先我们读入saber用来做为示例的图像 #读入图像代码,在此之前应当引入必要的opencv matplotlib numpy saber = cv2.i ...
- hdu1214 圆桌会议
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1214 HDU ACM集训队的队员在暑假集训时经常要讨论自己在做题中遇到的问题.每当面临自己解决不了的问 ...
- html5 图片墙
代码实例: <!DOCTYPE html> <html> <head> <style> body,html{ padding:0;margin:0;wi ...
- AGC003[BCDEF]题解
2018-12-28 有点累EF明天再写叭=v= 2018-12-29 update EF B - Simplified mahjong 可以注意到 一段连续的非0序列都可以凑出 就是显然%2=0的可 ...
- 计蒜客NOIP模拟D1T2
原题: 蒜头君有一棵有根树,树的每一边都有边权,蒜头君想知道任意两点间最短距离之和为多少.另外,由于各种原因,蒜头君的树的边的边权会发生若干次改变,蒜头君想让你告诉他,每一次改变后,任意两点间最短距离 ...
- js 中HTML的 onkeycode 和onkeydown属性事件
<!DOCTYPE html><html><head><script>function displayResult(){var x=document.g ...
- 【leetcode】416. Partition Equal Subset Sum
题目如下: 解题思路:对于这种判断是否的题目,首先看看动态规划能不能解决.本题可以看成是从nums中任选i个元素,判断其和是否为sum(nums)/2,很显然从nums中任选i个元素的和的取值范围是[ ...
- 【CF741D】Arpa’s letter-marked tree and Mehrdad’s Dokhtar-kosh paths(dsu on tree)
题意:我们称一个字符串为周驿东串当且仅当重排它的字符可以组成一个回文串. 给出一个n个点的有根树,根为1,每条边上有一个从a到v的字符,求每个点的子树中所有简单路径可以组成的周驿东串中的最长长度. n ...
- 记录从现在开始,我的第一篇blog
最近在读刘未鹏的<暗时间>,深受作者的启发,决定开始书写blog. 书写是为了更好的思考,希望自己能持之以恒的坚持做这件事情. 这本书很推荐给所有同学,不仅关于时间管理,执行力,心理学, ...