-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
37 lines (30 loc) · 1.27 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const net = require('net');
const port = 8080;
// Create a new TCP server.
const server = net.createServer();
// The server listens to a socket for a client to make a connection request.
// Think of a socket as an end point.
server.listen(port, function() {
console.log(`Server listening for connection requests on socket localhost:${port}`.);
});
// When a client requests a connection with the server, the server creates a new
// socket dedicated to that client.
server.on('connection', function(socket) {
console.log('A new connection has been established.');
// Now that a TCP connection has been established, the server can send data to
// the client by writing to its socket.
socket.write('Hello, client.');
// The server can also receive data from the client by reading from its socket.
socket.on('data', function(chunk) {
console.log('Data received from client:', chunk.toString());
});
// When the client requests to end the TCP connection with the server, the server
// ends the connection.
socket.on('end', function() {
console.log('Closing connection with the client');
});
// Don't forget to catch error, for your own sake.
socket.on('error', function(err) {
console.log(`Error: ${err}`);
});
});