preface
OSI network model is divided into seven layers, from bottom to top: physical layer, data link layer, network layer, transport layer, session layer, presentation layer, application layer, TCP protocol is in the transport layer.
TCP Node. Js
The NET module in Node.js provides the encapsulation of TCP protocol, using the NET module can easily build a TCP server, or build a client connected to the TCP server.
Net module creates a server
let net = require('net')
let server = net.createServer()
server.on('connection'.function(socket) {// Socket socket session, HTTP has request response console.log('connection success')
})
server.listen(3000, function () {
console.log('server start at 3000')})Copy the code
This creates a simple service. Start on port 3000 and listen for client connections. A socket is a readable and writable duplex stream, which can be understood as a session between a client and a server.
Receive data
socket.setEncoding('utf8')
socket.on('data'.function (data) {
console.log(data)
})
Copy the code
The response data
socket.write('nice to meet you')
Copy the code
Closing the Client
socket.end('end... ') // Close the clientCopy the code
Closing the Server
server.close(); Server.unref (); // If close is triggered, no new requests will be received. // No client connection will close itself (no close event will be triggered) server.on('close'.function () {
console.log('server closed')})Copy the code
After the close call, the server does not receive any new requests. When there is no client connection, the close event is triggered and the server is shut down
After the unref call, the server continues to accept new requests. When there is no client connection, the close event is not triggered and the server is shut down.
Set the maximum number of connections
server.maxConnections = 2; // Set the maximum number of connectionsCopy the code
Implementation of chat rooms
With the knowledge above, we can implement a chat room.
demand
- Number of current online users (maximum number of users that can be connected)
- The input
l:
To view the current user list. - The input
s:zs: hello
, send a message to Joe; - The input
r: ls
, rename yourself to ls; - The input
b: nice to meet you
Broadcast messages to other users
Create a service
let net = require('net');
let server = net.createServer((socket) => {
let key = socket.remoteAddress + socket.remotePort
console.log(key)
})
server.listen(3000, function () {
console.log('server start at 3000')})Copy the code
Cache client information
let client = {}
letServer = net.createserver ((socket) => {// Display welcome message server.maxConnections = 3; server.getConnections(function(err, count) {socket.write(' Welcome, current user${count}Always hold${server.maxConnections}\r\n ')}let key = socket.remoteAddress + socket.remotePort
client[key] = {nickname: 'anonymous',socket}
})
Copy the code
The client information is cached to the client, the IP address +port of the client is used as the key value, the nickname is anonymous by default, and the callback socket is saved.
Process instructions entered by the client
socket.setEncoding('utf8')
socket.on('data'.function (chunk) {
chunk = chunk.replace(/\r\n/,' ')
let [command, target, content] = chunk.split(':')
switch (command) {
case 'l'ShowList (socket);break;
case 's'CharTo (target,content, client[key].nickname);break;
case 'r': // Rename (key, target);break;
case 'b'Broadcast (key, target, client[key].nickname);break;
default:
break; }})Copy the code
Handles the implementation of functions
ShowList function implementation
function showList(socket) {
letForEach (user => {users.push(user.nickname)}) socket.write(' Current user list: \r\n${users.join('\r\n')} \r\n`)
}
Copy the code
The implementation of charTo function
function charTo(target, content, source) {
let targetSocket;
Object.values(client).forEach(user => {
if(user.nickname === target) {
targetSocket = user.socket
}
})
targetSocket.write(`${source}:${content}\r\n`)
}
Copy the code
The implementation of the rename function
functionrename(key, content) { client[key].nickname = content; Client [key].socket.write(' rename to:${content}\r\n`)
}
Copy the code
The implementation of broadcast function
function broadcast(key, content, nickname) {
Object.keys(client).forEach(user => {
if(user ! == key) { client[user].socket.write(`${nickname}: ${content}\r\n`)
}
})
}
Copy the code
Results of inspection
Our suggestion chat room is ready, we can use PuTTY this software as a client to send TCP requests;
Here are the results of my test.
conclusion
The process that oneself realizes a chat room is still very interesting, welcome the classmate that likes to tamper more exchange.