socket,socket.io,webSocket以及邏輯

一、socket:分爲一個服務端(server)和一個客戶端(client):html

server.js:jquery

const net = require("net");
const server = net.createServer();

//建立一個盒子將全部鏈接的用戶存放在這個盒子裏面
const clients = []


//用戶鏈接服務器
server.on("connection",(client)=>{

    //給每個用戶作一個標識 用來一會去作移除
    client.id = clients.length;
    clients.push(client);


    //服務器接收消息
   client.on("data",(data)=>{
       //服務器將接收到的消息發送給全部的用戶
        clients.forEach(item=>{
           if(item){
                item.write(data)
           }
        })
   })


   //當用戶離開的時候
   client.on("close",()=>{
        clients[client.id] = null;
   })
})


server.listen(9008);

client:git

const net = require("net");
const client = new net.Socket();
//能夠讓你獲取控制檯中書寫的信息
const readline = require("readline");
//建立文件讀寫流
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

//客戶端鏈接服務器
client.connect(9008,()=>{
  

    //客戶端接收服務端的消息

    client.on("data",(data)=>{
        console.log("服務器消息:"+data)
    })
})


//能夠讓用戶在控制檯中進行書寫 以及獲取到控制檯的信息
rl.on("line",(val)=>{
    client.write(val);
})

 

二、socket.io:index.html爲客戶端,server爲服務器(最優選擇)(github=>socket.io=>http://socket.io=>learn=>Get=>npm init - y =>cnpm install express -S=>跟着步驟走)github

server.js:web

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);



app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});

//當用戶鏈接的時候
io.on('connection', function(socket){
    console.log('有人來了');

    //服務端接收客戶端的消息
    socket.on('sendMsg', function(msg){
        io.emit('sendClientMsg', msg);
    })

     //當用戶離開的時候
  socket.on('disconnect', function(){
    console.log('我走了');
  });
});


http.listen(3000, function(){
  console.log('listening on *:3000');
    
 
});

index.html:express

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
  </body>
</html>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
  var socket = io();

    //客戶端向服務端發送消息
  $('form').submit(function(e){
      e.preventDefault(); // prevents page reloading
      //向服務器發送消息
      socket.emit('sendMsg', $('#m').val());

      $('#m').val('');
      return false;
    });



    //客戶端接收服務器的消息
    socket.on('sendClientMsg', function(msg){
      $('#messages').append($('<li>').text(msg));
    });
</script>

 

三、webSocket:index.html爲客戶端,server爲服務端  (H5新增,有兼容性,需下載第三方的包:npm init -y   cnpm install  ws  -S;github中,將文檔copy下來進行修改便可)npm

server.js:服務器

const WebSocket = require('ws');
//建立服務器
const server = new WebSocket.Server({ port: 9000 });
//鏈接服務器
server.on('connection', (client) =>{
    //接收客戶端的消息
  client.on('message', (data)=>{
    //將接收到的消息發送給全部客戶端
    server.clients.forEach((item)=> {
        //檢測用戶是否存在  
        if (item.readyState === WebSocket.OPEN) {
                item.send(data);
         }
      });


  });
});

index.html:app

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <input type="text" id="input"/>
    <button id="btn">點擊</button>
    <ul id="list">
        
    </ul>
</body>
</html>
<script>
    //客戶端鏈接服務器
    var  client = new WebSocket("ws://10.9.14.136:9000");

    //接收服務器的消息
    client.onmessage = function(e){
       let msg = e.data;
       var li = document.createElement("li");
       li.innerText = '服務端的消息:'+msg;

       list.appendChild(li)
    }

    //向服務器發送消息
    btn.onclick = function(){
        var val = input.value;
        input.value = "";

        client.send(val);
    }


</script>

 總結:(羣聊邏輯)socket

①建立一個羣

②將好友拉到這個羣

③鏈接共同的服務器

④發送消息的時候將消息發送給服務器,服務器轉發給包括本身的全部用戶

 

①A用戶發送一條消息=>服務器

②服務器接收消息後=>給全部用戶發消息

③若是有用戶斷開連接,就不用給他發

相關文章
相關標籤/搜索