Created
October 16, 2012 06:19
-
-
Save ruzz311/3897499 to your computer and use it in GitHub Desktop.
TCP socket with Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var net = require('net'), server, s; | |
// socket events | |
s = { | |
onStart: function(){ | |
console.log('server started') | |
}, | |
onClientConnect: function(conn){ | |
console.log('connected', conn); | |
conn.on('end', s.onClientEnd); | |
conn.on('data', s.onClientData); | |
conn.write('What up NodeLabs KC?\r\n'); | |
conn.pipe(conn); | |
}, | |
onClientData: function(buf){ | |
var str = buf.toString('utf8'); | |
bytes = Buffer.byteLength(str, 'utf8'), | |
len = buf.length; | |
console.log('client -> server data is %s characters and %s bytes long.', len, bytes); | |
console.log('client -> server raw data: ', buf); | |
console.log('client -> server message: "%s"', str); | |
}, | |
onClientEnd: function(){ | |
console.log('disconnected') | |
} | |
}; | |
// Create & Start | |
server = net.createServer(s.onClientConnect); | |
server.listen(3333, s.onStart); | |
/** (assumed *nix based OS) | |
* | |
* Start socket server | |
* -> $ node sockets-1.0.js) | |
* | |
* telnet into your server you just started. you should see "What up NodeLabs KC?" | |
* -> $ telnet 127.0.0.1 3333 | |
* | |
* At this point you are in a telnet session with your TCP server. | |
* You can send messages to the server by entering message and press enter. | |
* -> $ "Mr. Watson - come here - I want to see you." <return> | |
* | |
* To exit telnet, press "control"+"]" and type "quit" | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment