用node.js模拟服务器和客户端

时间:2023-01-09 17:09:33

服务器

代码

var net = require("net")
var server = net.createServer();
server.listen(12306,"127.0.0.1")
 
server.on("listening",function(){
    console.log(server.address())
    console.log("服务启动了")
})
 
server.on('connection',function(socket){
    console.log('有新的连接')
    socket.on('data',function(data){
          console.log(data.toString()) 
          socket.write("hello client") 
    })
    socket.on('close',function(){
        console.log("客户端已关闭")
        server.close()
    })
})
 
server.on('close',function(){
    console.log('服务器已关闭')
})

 


客户端

代码

var net= require("net");
var socket = net.connect(12306,"127.0.0.1")
socket.on('connect',function(){
    console.log('已连接服务器')
    console.log(socket.remoteAddress);//服务器地址
    console.log(socket.remotePort)//服务器端口
    console.log(socket.localAddress)//本地地址
    console.log(socket.localPort)//本地端口
})
socket.on('data',function(data){
    console.log(data.toString()) 
    socket.end()
})
socket.on('close',function(){
    console.log("连接已关闭")
})
socket.write("hello server")