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!");
- });
参考:node.js v0.10.12 manual & documentation
node 入门
tcp scoket programming in node.js