nodejs 创建tcp/udp服务器和客户端

TCP

server

// https://nodejs.org/api/net.html

const net = require("net");

// https://nodejs.org/api/net.html#net_net_createserver_options_connectionlistener
// https://nodejs.org/api/net.html#net_class_net_socket
const server = net.createServer((c /*net.Socket*/) => {
  console.log("client connected");

  c.setEncoding("utf-8");
  c.on("data", (data) => {
    // 处理发送的数据,telnet连接后,会把键盘的输入事件发送过来
    console.log(data);
    c.write("hello\r\n");
  });
  c.on("end", () => {
    console.log("client disconnected");
  });

  // https://*.com/questions/36314892/when-should-i-use-socket-pipe-on-nodejs-net-socket
  // tcp 是双向的,pipe会把发送来的信息原封不动的返回去
  // c.pipe(c);
});
server.on("error", (err) => {
  console.log(err.message);
});
server.listen(5000, () => {
  console.log("server bound");
  console.log(server.address());
});

// 测试
// telnet localhost 5000

client

const net = require("net");

// https://nodejs.org/api/net.html#net_net_createconnection_options_connectlistener
const client = net.createConnection({ port: 5000 }, () => {
  console.log("connected to server!");
  client.write("i‘m tcp client. \r\n");
});
client.on("data", (data) => {
  console.log(data.toString());
  client.end();
});
client.on("end", () => {
  console.log("disconnected from server");
});

tcp流:
nodejs 创建tcp/udp服务器和客户端

UDP

server

// https://nodejs.org/api/dgram.html

const dgram = require("dgram");
const server = dgram.createSocket("udp4");

server.on("error", (err) => {
  console.log(`server error:\n${err.stack}`);
  server.close();
});

const message = Buffer.from(`hi\n`);
server.on("message", (data, rinfo) => {
  console.log(data.toString());
  console.log(rinfo);
  server.send(message, rinfo.port, rinfo.address, (err) => {
    if(err) console.log(err);
  });
});

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

server.bind(5000);

client

const dgram = require("dgram");
const message = Buffer.from(`i‘m udp client.`);
const client = dgram.createSocket("udp4");

client.on("error", (err) => {
  console.log(err);
});

client.on("message", (data, rinfo) => {
  console.log(data.toString());
});

client.send(message, 5000, "localhost", (err) => {
  // client.close();
});

udp流:
nodejs 创建tcp/udp服务器和客户端

nodejs 创建tcp/udp服务器和客户端

上一篇:curlPost和curlGet 请求链接


下一篇:一次使用IDEA中HTTP Client的经历