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 的服务通常是架构层面上的考虑. 因为它天生就具有很好的跨平台跨语言的集成能力 ...
随机推荐
- adb shell常用命令总结
一.文件操作相关命令 1.文件操作命令 子命令 参数 说明 cd 无 进入目录 cat [-beflnstuv] [-B bsize] [file...] 查看文件内容-n:显示行号-b:显示行号,但 ...
- XSS——跨站脚本攻击
跨站点脚本攻击:通过对网页注入恶意脚本,成功地被浏览器执行,来达到攻击的目的. 一.XSS攻击类型与原理1. 反射型XSS攻击非持久性攻击,黑客使用社交性的交互技巧诱导用户点击访问目标服务器的链接,但 ...
- Android禁止输入表情符号
在我们Android开发的项目中,难免有要求在输入框中禁止输入表情,所以呢,写了一个输入框禁止输入表情的demo,供大伙参考 效果图 如图显示,如果用户输入了表情字符,会提示. EmojiFilter ...
- Java笔试题-List l = new List()
前言: 最近遇到的一道很基础的题,有时候大家可能离开了编译器就不行了. import java.util.List; /** * * @author catchegg * create date: 2 ...
- Tomcat架构与原理
Tomcat架构与原理 架构图 原理 ①.用户点击网页内容,请求被发送到本机端口8080,被在那里监听的Coyote HTTP/1.1 Connector获得. ②.Connector把该请求交给它所 ...
- 《程序员的呐喊》:一个熟悉多种语言的老程序员对编程语言、开发流程、google的战略等的思考,比较有趣。 五星推荐
作者熟悉二三十种编程语言,写了20多年代码.本书是作者对编程语言.开发流程.google的战略等的思考.比较有趣. 前面部分是作者对编程语言的一些思考.作者鄙视C++, Java,面向对象.比较有趣的 ...
- Sass-unitless()函数
unitless() 函数相对来说简单明了些,只是用来判断一个值是否带有单位,如果不带单位返回的值为 true,带单位返回的值为 false: >> unitless(100) true ...
- mongodb 索引基础
一 .索引基础: MongoDB的索引几乎与传统的关系型数据库一模一样,这其中也包括一些基本的优化技巧.下面是创建索引的命令: > db.test.ensureIndex({&quo ...
- 03.父工程pom、整合测试、SpringBootApplication注解
父工程 idea点击spring-boot-starter-parent找到父工程spring-boot-dependencies模仿配置 父工程 <?xml version="1.0 ...
- DC/DCT/DCG 差别和联系
在dc家族系列中,DC_V,DC_E为根本的DC(Design Compiler)对象,具有dc所具有的根本fearture,DC在synopys对象系列中地位,无足轻重,也是业界应用最普遍的综合对象 ...