Node.js Socket 客户端和服务端通讯并且服务端返回客户端 IP
之乎者也 Lv3

用来看路由器WAN口IP

服务端代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const net = require('net');

const server = net.createServer((socket) => {
console.log('Client connected');

const clientAddress = socket.remoteAddress;
console.log(`Client IP address is ${clientAddress}`);

socket.on('data', (data) => {
console.log(`Received from client: ${data}`);
socket.write(`Hello from server! Your IP address is ${clientAddress}`);
});

socket.on('end', () => {
console.log('Client disconnected');
});
});

server.listen(3000, () => {
console.log('Server started on port 3000');
});

客户端代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const net = require('net');

const client = new net.Socket();

client.connect(3000, 'localhost', () => {
console.log('Connected to server');

client.write('Hello from client!');
});

client.on('data', (data) => {
console.log(`Received from server: ${data}`);
client.destroy();
});

client.on('close', () => {
console.log('Connection closed');
});

在客户端代码中,我们连接到了服务端并发送了一条消息。在收到服务端的回复后,客户端关闭了连接。

在实际使用中,可以根据需要更改客户端和服务端代码,并在需要发送和接收数据时进行修改。服务端也可以使用 Socket.io 等其他第三方库实现实时通讯功能。