websocket

开发选择
websocket的应用场景,像客服,股票等;
socket.io框架,是基于node.js的websocket框架,封装成自定义事件,使用方便。对于低版本ie也做了处理。

今天我们学习websocket,不用框架

H5用原生的websocket,

websocket的状态码:
0 :对应常量CONNECTING (numeric value 0),
正在建立连接连接,还没有完成。The connection has not yet been established.
1 :对应常量OPEN (numeric value 1),
连接成功建立,可以进行通信。The WebSocket connection is established and communication is possible.
2 :对应常量CLOSING (numeric value 2)
连接正在进行关闭握手,即将关闭。The connection is going through the closing handshake.
3 : 对应常量CLOSED (numeric value 3)
连接已经关闭或者根本没有建立。The connection has been closed or could not be opened.

websocket,原生,

今天这个分享,牵涉的内容:
客户端:开发环境gulp,搭建的单页开发环境
客服端:天工基础模板1.1.0
服务端:node.js

第一步:理想架构分享

https://www.jianshu.com/p/76b8e5418e7f

第二步:写看下效果,我们要实现的功能

1、实现一对一聊天;
2、实现群发功能

第三步:代码实现

只写服务端的:客服端牵扯公司业务,不做展示

/*
* @Author: wang
* @Date:   2018-12-06 21:04:31
* @Last Modified by:   wang
* @Last Modified time: 2019-01-20 20:11:25
*/

var http = require("http");
var fs = require("fs");
// var io = require("socket.io");
var url = require("url");
var server = require('ws').Server;
var wss = new server({ port: 8181,verifyClient: ClientVerify });
var app=http.createServer(function(req,res){
    if(req.url == "/"){
        fs.readFile("index.html",function(err,data){
            res.end(data)
        })
    }else if(req.url == "/socket.io.js"){
        fs.readFile("socket.io.js",function(err,data){
            res.writeHead(200,{"Content-type":"text/javascript"})
            res.end(data)   //这里没有用socket.io.js
        })
            
        }else{
            res.end("end");
        }
    
})

app.listen(8080)
var  arr = {};
var userName ;
var  wangWs = {}
var toWs
var i=0;
function ClientVerify(info) {
    // console.log(info)
//    var ret = false;//拒绝
   var params = url.parse(info.req.url, true).query;
console.log(params)
       userName = params["name"];
console.log(userName)
//      console.log(params["id"]== "luoc83" , params["key"] == "12345",i++)
//    if (params["id"] == "luoc838"||params["id"] == "luoc83" &¶ms["key"] == "12345") {
//  console.log(params["id"])

//         ret = true;//通过

//    }
//    return ret;  
     return true;

}

wss.on('connection', function (ws){
   console.log('client connected');
   wangWs[userName] = ws;
   ws.on('message', function (message) {
        console.log(message,"mmmmmmmm")
//         ws.send(message);
        var data = {}
        // for(let  j in wangWs){
        //  console.log(j)
        //  var toWs = wangWs[j]
        //    toWs.send(message) ;//群发消息
        // }
        var  mes =  JSON.parse(message);
        if(wangWs[mes.requestObject.toUserId]){
             toWs =  wangWs[mes.requestObject.toUserId];
             toWs.send(message);//一对一发消息
        }else{
            toWs =  wangWs[userName];
            toWs.send(message);
        }
        var x= 0
        function FunTimer(){
            setTimeout(()=>{
                if(wangWs.son &&x <5){
                    ++x;
                    wangWs.son.send( JSON.stringify(data)) ;
                    FunTimer()
                }
            }, 1000)
        }
        if(mes.cmdCode === 1){
            FunTimer()
        }
        
    
   });
   ws.on('close', function (close) {
        console.log("client closed");
   });

});


  • <script>alert("xx")</script>
  • 你可能感兴趣的:(websocket)