Node——创建websocket及客户端连接

【方法一:net】

cnpm i -S net
const net = require('net');

const server = net.Server()

server.on("listening", () => {
  console.log("listening")
})

server.on("connection", (socket) => {
  socket.on("data", buf => {
    console.log(buf)
  })
  socket.on('error', (e) => {
    console.log("error");
  })
  socket.on('end', (e) => {
    console.log('socket end');
  })
  socket.on("close", () => {
    console.log("socket close")
  })
})

server.listen(10010)

【方法二:nodejs-websocket】

cnpm i -S nodejs-websocket
const ws = require("nodejs-websocket")

ws.createServer((conn) => {
  conn.on("text", (str) => {
    console.log(str)
  })
  conn.on("close", (code, reason) => {
    console.log(`close`)
  });
  conn.on("error", (code, reason) => {
    console.log(`close`)
  });
}).listen(10010)

【客户端连接】

const handleConnet = () => {
  let ws = new WebSocket("ws:127.0.0.1:10010")
  ws.onopen = ()=>{
    console.log("已连接")
    ws.send("hello websocket")
  }
  ws.onmessage = (data)=>{
    console.log("接收的参数",data)
  }
  ws.onerror = (e)=>{
    console.log(e)
  }
};

你可能感兴趣的:(Node,websocket,网络协议,网络)