nodejs & tcp socket

服务端

var net = require('net');
//模块引入
var listenPort = 8080;//监听端口
var server = net.createServer(function(socket){
  // 创建socket服务端
  console.log('connect: ' +
    socket.remoteAddress + ':' + socket.remotePort);
  socket.setEncoding('binary');
  //接收到数据
  socket.on('data',function(data){
    console.log('client send:' + data);
  });
socket.write('Hello client!\r\n');
 // socket.pipe(socket);
  //数据错误事件
  socket.on('error',function(exception){
    console.log('socket error:' + exception);
    socket.end();
  });
  //客户端关闭事件
  socket.on('close',function(data){
    console.log('client closed!');
     // socket.remoteAddress + ' ' + socket.remotePort);
  });
}).listen(listenPort);
//服务器监听事件
server.on('listening',function(){
  console.log("server listening:" + server.address().port);
});
//服务器错误事件
server.on("error",function(exception){
  console.log("server error:" + exception);
});

客户端

var net = require('net');
var port = 8080;
var host = '127.0.0.1';
var client= new net.Socket();
//创建socket客户端
client.setEncoding('binary');
//连接到服务端
client.connect(port,host,function(){
  client.write('hello server');
  //向端口写入数据到达服务端
});
client.on('data',function(data){
  console.log('from server:'+ data);
  //得到服务端返回来的数据
});
client.on('error',function(error){
//错误出现之后关闭连接
  console.log('error:'+error);
  client.destory();
});
client.on('close',function(){
//正常关闭连接
  console.log('Connection closed');
});

参考地址:
https://blog.csdn.net/lockey23/article/details/76408891

标签: none

添加新评论