Created
September 18, 2018 19:27
-
-
Save JoeKarlsson/7811cab7f1a1fe62c8216eb5ac9105f0 to your computer and use it in GitHub Desktop.
Intro to NodeJS - using the net module and building a client and server
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
const net = require('net'); | |
const options = { | |
'port': 8080, | |
'host': '127.0.0.1' | |
}; | |
// creates a socket connection to a server | |
const client = net.connect(options, () => { | |
console.log('Connected to Server!'); | |
client.write('Hello server'); | |
}); | |
// handles data received | |
client.on('data', (data) => { | |
console.log('data: ', data); | |
}); | |
// Take input from the commandline | |
process.stdin.on('readable', () => { | |
var chunk = process.stdin.read(); | |
if (chunk !== null) { | |
client.write(chunk) | |
} | |
}); |
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
const net = require('net'); | |
const server = net.createServer((request) => { | |
// handles data received | |
request.on('data', (data) => { | |
console.log('Request recieved /n', data.toString()); | |
}) | |
request.write('Hello Client'); | |
request.end(); | |
// Handles request ended | |
request.on('end', () => { | |
console.log('Connection Closed'); | |
}) | |
}) | |
// Listen for events on port 8080 | |
server.listen({ port: 8080 }, () => { | |
const address = server.address(); | |
console.log(`Opened server on ${address.port}`) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment