我们可以利用node.js中内置的net模块创建socketserver和socketclient,实现一个简单的基于console的点对点通信通信。一、使用net模块建立socket客户端1、引入包constnet=require('net');2.与指定IP地址和端口号的服务器建立连接constclient=net.connect({port:number,host:string},()=>{});其中,port参数以数值型填写服务器的端口号,host参数以字符串型填写服务器的IP地址。如果不写host参数,则默认与本机指定端口建立连接。当新创建的客户端与指定服务器建立连接时,回调函数被触发。回调函数没有参数,回调函数内部使用自定义变量client代表客户端。3.客户端和服务器之间发送和接收数据,在客户端和服务器建立连接的回调函数中使用client.write();要从客户端向服务器发送数据,请使用client.on('data',(chunk)=>{});可以接收服务器发送的数据,当接收到服务器发送的数据时触发回调函数,chunk.toString()可以得到服务器发送的数据内容。以下是client.js的示例代码:constreadline=require('readline');constnet=require('net');constrl=readline.createInterface(process.stdin,process.stdout);const客户端=净。connect({port:2080,host:'192.168.155.1'},()=>{rl.on('line',(line)=>{client.write(line.trim());});客户端.on('data',(chunk)=>{console.log(chunk.toString());});});二、使用net模块建立socket服务器1、引入包constnet=require('net');2.创建socket服务器constserver=net.createServer((socket)=>{});这意味着创建了一个套接字服务器,并使用一个自定义服务器变量来接收它。当有客户端与服务器端建立连接时,会触发回调函数的执行,回调函数内部使用指定的形参socket对象。3.让新创建的socketserver监听指定的端口。socket服务器创建后,必须监听操作系统的特定端口,否则没有意义。varport=2080;server.listen(port,(err)=>{if(err){console.log('端口被占用!');returnfalse;};console.log(`服务器正常启动,听${port}端口!`);});为了避免端口被占用的情况,可以设置port=0;,0不是一个标准的端口号,传0的作用是系统会随机分配一个当前运行的系统中未被占用的端口号.在步骤2的回调函数中,使用socket.remoteAddress获取远程客户端连接本机的IP地址,使用socket.remotePort获取远程客户端连接本机的端口号,使用socket.localAddress可以获取机器的IP地址,使用socket.localPort获取套接字服务器使用的端口号。使用socket.write();从服务器向客户端发送数据,使用socket.on('data',(chunk)=>{});接收客户端发送的数据,当客户端发送有数据时触发回调函数,chunk.toString()可以获取到客户端发送的数据内容。以下是socket.js的示例代码:constnet=require('net');constreadline=require('readline');constrl=readline.createInterface(process.stdin,process.stdout);常量服务器=网络。createServer((socket)=>{rl.on('line',(line)=>{socket.write(line.trim());});socket.on('data',(chunk)=>{console.log(chunk.toString());});});varport=2080;server.listen(port,(err)=>{if(err){console.log('端口被占用!');returnfalse;};console.log(`服务器正常启动,监听${port}端口!`);});先在控制台启动server.js,再启动client.js文件,就可以实现两端之间基于控制台的点对点消息收发。如下所示。
