zoukankan      html  css  js  c++  java
  • node模拟socket

    什么是Socket?
    网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket。

    Socket通信流程

    基于net模块实现socket

     服务端SocketServer.js

    var net = require('net')
    
    // 声明一个客户端socket
    var client = new net.Socket()
    
    client.setEncoding = 'UTF-8'
    
    // 连接服务器
    client.connect(9000, '127.0.0.1', function () {
      client.write('您好')
    })
    
    // 客户端接收服务端数据
    client.on('data', function (data) {
      console.log('服务端传来:' + data)
      say()
    })
    
    // 客户端关闭
    client.on('close', function () {
      console.log('connection closed');
    })
    
    // 定义输入界面
    var readline = require('readline')
    
    var r = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    })
    
    function say() {
      r.question('请输入:', (inputStr) => {
        if (inputStr == 'bye') {
          client.destroy()
          r.close()
        } else {
          client.write(inputStr + '
    ')
        }
      })
    }
    View Code

    客户端SocketClient.js

    var net = require('net')
    
    var chatServer = net.createServer()
    
    // client 对象集合
    var clientMap = new Object()
    
    var i = 0
    
    // 创建一个连接
    chatServer.on('connection', function (client) {
      console.log('客户端有人连接~')
    
      // 用自然数记录用户的名字
      client.name = ++i
    
      // 记录client对象
      clientMap[client.name] = client
    
      // 获取用户端发送来的数据
      client.on('data', function (data) {
        console.log('客户端传来:' + data)
        broadcast(data, client)
      })
    
      // 错误处理
      client.on('error', function (err) {
        // console.log(err);
        client.end()
      })
    
      // 客户端关闭处理
      client.on('close', function (data) {
        delete clientMap[client.name]
        broadcast(client.name + '下线了', client)
      })
    
    })
    
    // 服务端广播数据给客户端
    function broadcast(data, client) {
      for (var key in clientMap) {
        // 发送数据
        clientMap[key].write(client.name + ' 说:' + data + '
    ')
      }
    }
    
    // 监听端口
    chatServer.listen(9000)
    View Code

    启动服务端:

    node SocketServer.js

    使用多个窗口启动客户端:

    node SocketClient.js

    模拟websocket

    服务端

    WsServer.js

    // 服务创建
    var WebsocketServer = require('ws').Server
    wss = new WebsocketServer({port: 9000})
    
    var clientMap = new Object()
    var i = 0
    
    wss.on('connection', function (ws) {
      console.log(ws + '上线了');
      ws.name = ++i
    
      clientMap[ws.name] = ws
    
      // 接收客户数据
      ws.on('message', function (msg) {
        broadcast(msg, ws)
      })
    
      // 客户端关闭监听
      ws.on('close', function () {
        delete clientMap[ws.name]
        console.log(ws.name + '离开');
      })
    })
    
    function broadcast(msg, ws) {
      for (var key in clientMap) {
        clientMap[key].send(ws.name + '说' + msg)
      }
    }
    View Code

    客户端:

    WsClient.js

    var ws = new WebSocket('ws://127.0.0.1:9000/')
    
    ws.onopen = function () {
      ws.send('大家好')
    }
    
    ws.onmessage = function (event) {
      var chatroom = document.querySelector('#chatroom')
      chatroom.innerHTML += '<br />' + event.data
    }
    
    ws.onclose = function () {
      console.log('Closed');
    }
    
    ws.onerror = function (err) {
      console.log(err);
    }
    View Code

    index.html

    <!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>
      <style>
        #chatroom {
          width: 400px;
          height: 300px;
          overflow: auto;
          border: 1px solid blue;
        }
      </style>
    </head>
    <body>
      <h1>WebSocket</h1>
      <div id="chatroom"></div>
      <input type="text" name="sayinput" id="sayinput" value="">
      <input type="button" name="send" id="send" value="发送">
    
      <script src="./WsClient.js"></script>
      <script>
        function send() {
          var sayinput = document.querySelector('#sayinput')
          ws.send(sayinput.value)
          sayinput.value = ''
        }
        document.querySelector('#send').onclick = function () {
          send()
        }
        document.body.onkeyup = function (event) {
          if (event.keyCode == 13) {
            send()
          }
        }
      </script>
    </body>
    </html>
    View Code

     socket.io的使用

    SocketIoServer.js

    var http = require('http')
    var app = http.createServer()
    var io = require('socket.io')(app);
    
    app.listen(9001);
    
    io.on('connection', function (socket) {
      //socket.name = ++i
      //onlineusers[socket.name] = socket
      socket.on('my other event', function (data) {
        // for (var key in onlineusers) {
        //   onlineusers[key].emit('news', { msg: data.my })
        // }
        socket.emit('news', { msg: data.my });
        socket.broadcast.emit('news', { msg: data.my });
      });
    });
    View Code

    index.html

    <!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>Socket.io</title>
      <style>
        #chatroom {
          width: 400px;
          height: 300px;
          overflow: auto;
          border: 1px solid blue;
        }
      </style>
    </head>
    <body>
      <h1>Socket.io</h1>
      <div id="chatroom"></div>
      <input type="text" name="sayinput" id="sayinput" value="">
      <input type="button" name="send" id="send" value="发送">
    
      <script src="./socket.io.js"></script>
      <script>
        var socket = io('http://localhost:9001');
        socket.on('news', function (data) {
          document.querySelector('#chatroom').innerHTML += data.msg + "<br/>"
        });
    
        function send() {
          var sayinput = document.querySelector('#sayinput')
          socket.emit('my other event', { my: sayinput.value });
          sayinput.value = ''
        }
        document.querySelector('#send').onclick = function () {
          send()
        }
        document.body.onkeyup = function (event) {
          if (event.keyCode == 13) {
            send()
          }
        }
      </script>
    </body>
    </html>
    View Code

     express脚手架( express-generator)+socketio

      https://my.oschina.net/freddon/blog/529599

  • 相关阅读:
    5R(康奈尔)笔记法
    【软件】MyEclipse 显示行数及Eclipse修改字体
    Linux运维工程师必备的十个技能点
    centos下部署LAMP环境(Linux+Apache+mysql+php)(转载文章:https://www.cnblogs.com/apro-abra/p/4862285.html)
    MySQL之show命令 (转载https://www.cnblogs.com/andy6/p/6171945.html)
    MySQL安装完成后重置密码
    MySQL面试题
    mysql运维必备知识点(转载至其他作者)
    centos 7 下安装部署mysql 5.7
    Linux服务部署之NTP时间服务器
  • 原文地址:https://www.cnblogs.com/fanlinqiang/p/7808404.html
Copyright © 2011-2022 走看看