node模拟socket

Posted FAN

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 + \'\\n\')
    }
  })
}
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 + \'\\n\')
  }
}

// 监听端口
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

 

以上是关于node模拟socket的主要内容,如果未能解决你的问题,请参考以下文章

Node.js创建服务器和模拟客户端请求

Node.js JavaScript 片段中的跳过代码

Sinon.js:无法模拟 node.js 网络对象

HTTP 状态代码 200 但页面未加载 Node.js Socket.io -- 使用 Socket.io 的 Node.js 教程,Daniel Nill,fs.readFile(),socket

Python干货socket中的listen()参数(数字)到底代表什么?

需要帮助理解 Socket.io(node.js) 中的以下 jQuery 代码?