12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- var server = require("http").createServer();
- module.exports = class WebSocketServer {
- constructor() {
- this.connMap = new Map();
- this._pageMap = new Map();
- this._count = 0;
- this._users = [];
- }
- create() {
- this.io = require("socket.io")(server, {
- path: "/test",
- serveClient: false,
- // below are engine.IO options
- pingInterval: 10000,
- pingTimeout: 5000,
- cookie: false,
- });
- server.listen(3000, { origins: "*" });
- this.io.on("connection", (socket) => {
- this._count = this._count >= this._users.length ? 0 : this._count;
- let user = socket.handshake.query
- this._users.push(user)
- let userId = user.role === 'customer' ? 'customerId' : 'agentId'
- let friendId = user.role !== 'customer' ? 'customerId' : 'agentId'
- this.connMap.set(userId, socket);
- socket.emit('vr_request', { userInfo: user });
- this._count++;
- socket.on("getJson", (data) => {
- console.log("收到的信息为:" + data);
- let msg = data;
- let connTemp = this.connMap.get(friendId);
- let action = msg.content.action
-
- socket.emit("action", action,()=>{
- console.log(action)
- });
- !!connTemp && this.sendText(connTemp, msg, (msgSendFinally) => {
- console.log(msgSendFinally)
- });
- });
- console.log("WebSocket服务端建立完毕");
- socket.on("disconnect", function (reason) {
- // this.connMap[userId] && (delete this.connMap[userId])
- // console.log(this.connMap)
- console.log("关闭连接", reason);
- });
- socket.on("error", function (reason) {
- console.log("异常关闭", reason)
- });
- return this;
- });
- }
- close() {
- this.server.disconnect(true);
- }
- sendText(socket, msg, cbOk) {
- const msgSendFinally = msg;
- let action = msg.content.action
- socket.emit("action", action,()=>{
- console.log(action)
- });
- socket.emit("vr_response", msgSendFinally,()=>{
- cbOk && cbOk(msgSendFinally);
- });
- }
- };
|