7年游戏服务器开发,擅长c/c++,javesript,php;熟悉linux,mysql/redis,elasticsearch;开源爱好者.github : https://github.com/yuyunliuhen
全部博文(26)
分类: JavaScript
2013-07-19 08:17:24
点击(此处)折叠或打开
- // tcp_server.js
- var net = require("net");
- var HOST = "127.0.0.1"
- var PORT = 9876
- var BUFSIZE = 256
- var buf = new Buffer(BUFSIZE);
- // connection 's event prototype is function(sock), you can also use net.createServer( function(sock){ ... } );
- // the funcetion pass to net.createServer becomes the event handler for 'connection' event;
- // the sock object the call back function receive unique for each connection.
- function onConnection(sock)
- {
- console.log("connected :" + sock.remoteAddress + " " + sock.remotePort);
- // add a 'data' event handler to this instance of socker
- sock.on("data",function(buf)
- {
- console.log("data from clinet: " + sock.remoteAddress + " : " + buf.toString('utf8', 0, buf.length));
- // write back data to the connection of socket
- sock.write(buf.toString('utf8', 0, buf.length));
- });
- // add a 'close' event handler to this instance of socker
- sock.on("close",function(data)
- {
- console.log("closed " + sock.remoteAddress + " " + sock.remotePort);
- });
- }
- // create a server instance, you also can use another way,
- /*
- var server = net.createServer();
- server.listen(PORT,HOST);
- server.on('connection',function(sock){...} );
- */
- var server = net.createServer( false,onConnection );
- // listen at PORT HOST
- server.listen(PORT,HOST);
- console.log("server listen on " + HOST + " : " + PORT);
点击(此处)折叠或打开
- // tcp_client.js
- var net = require("net");
- var HOST = "127.0.0.1"
- var PORT = 9876
- var BUFSIZE = 256
- var buf = new Buffer(BUFSIZE);
- var client = new net.Socket();
- // open a connection for a gived socket
- client.connect(PORT,HOST,function()
- {
- console.log("connect to :" + HOST + " : " + PORT);
- // write data to server
- var len = buf.write("0123456789");
- console.log("data :" + buf.toString('utf8', 0, len));
- client.write(buf);
- });
- // add a 'data' event handler for the client socket,the callback funtion receive the data whick server give back
- client.on("data",function(buf)
- {
- console.log("data :" + buf.toString('utf8', 0, buf.length));
- client.write(buf);
- });
- // add a 'close' event handler for the client socket
- client.on("close",function()
- {
- console.log("connect closed!");
- });