Want to write a simple game server with Nodejs, is studying ...
Service Area Code Server.js
var net = require (' net '); var HOST = ' 127.0.0.1 '; var PORT = 8080;var Chatserver = Net.createserver (); var clientlist = [];ch Atserver.on (' Connection ', function (client) {client.name = client.remoteaddress + ': ' + client.remoteport;console.log (' Connect request from ' + Client.name ' client.settimeout (5*1000); Client.write (' hi!\n '); Clientlist.push (client); Client.on (' Data ', function (data) {Broadcast (data, client);}); Client.on (' End ', function () {Clientlist.splice (Clientlist.indexof (client), 1);}); Client.on (' Close ', function () {Console.log (' close: ' + client.name);}); Client.on (' timeout ', function () {client.end ();}) Client.on (' Error ', function (Error) {Console.log (error); Connection.end ();}); function broadcast (message, client) {var cleanup = [];for (var i = 1; i < clientlist.length; i++) {if (client!== Clientlis T[i]) {if (clientlist[i].writable) {clientlist[i].write (client.name + ' says: ' + message);} else {Cleanup.push ( Clientlist[i]); Clientlist[i].destroy ()}}}for (var i = 0; i < Cleanup.lengtH i++) {Clientlist.splice (Clientlist.indexof (Cleanup[i]), 1);};} Chatserver.listen (port, host); Console.log (' Server listening on ' + HOST + ': ' + PORT ');
Test the customer-side code Client.js
var net = require (' net '); var HOST = ' 127.0.0.1 '; var PORT = 8080;var client = new Net. Socket (); Client.connect (port, host, function () {Console.log (' Connect to ' + HOST + ': ' + PORT); Client.write (' Connet reques T from ' + + HOST + ': ' + PORT + ' \ n '); Client.destroy ();}); Client.on (' Close ', function () {Console.log (' connetion closed. ');});
Nodejs socket Long connection server and test client