使用node.js的net模塊能很快的開發出基於TCP的服務端和客戶端。直接貼代碼。
server.js
/**
* Created with JetBrains WebStorm.
* User: Administrator
* Date: 12-10-26
* Time: 下午3:44
* To change this template use File | Settings | File Templates.
*/
var net = require('net');
var timeout = 20000;//超時
var listenPort = 7003;//監聽端口
var server = net.createServer(function(socket){
// 我們獲得一個連接 - 該連接自動關聯一個socket對象
console.log('connect: ' +
socket.remoteAddress + ':' + socket.remotePort);
socket.setEncoding('binary');
//超時事件
// socket.setTimeout(timeout,function(){
// console.log('連接超時');
// socket.end();
// });
//接收到數據
socket.on('data',function(data){
console.log('recv:' + data);
});
//數據錯誤事件
socket.on('error',function(exception){
console.log('socket error:' + exception);
socket.end();
});
//客戶端關閉事件
socket.on('close',function(data){
console.log('close: ' +
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);
});
client.js
/**
* Created with JetBrains WebStorm.
* User: Administrator
* Date: 12-10-26
* Time: 下午3:56
* To change this template use File | Settings | File Templates.
*/
var net = require('net');
var port = 7003;
var host = '127.0.0.1';
var client= new net.Socket();
client.setEncoding('binary');
//連接到服務端
client.connect(port,host,function(){
client.write('hello my client');
});
client.on('data',function(data){
console.log('recv data:'+ data);
});
client.on('error',function(error){
console.log('error:'+error);
client.destory();
});
client.on('close',function(){
console.log('Connection closed');
});