在TypeScript中监听来自套接字的消息并将其打印到控制台,可以通过以下步骤实现:
net
模块和readline
模块,以及TypeScript的相关库。import * as net from 'net';
import * as readline from 'readline';
net
模块创建一个套接字服务器,并指定服务器的端口号。const server = net.createServer((socket) => {
// 处理套接字连接
});
const port = 3000; // 服务器端口号
server.listen(port, 'localhost', () => {
console.log(`Server listening on port ${port}`);
});
connection
事件,当有客户端连接时,会触发该事件,并传递一个套接字对象。server.on('connection', (socket) => {
console.log('Client connected');
// 处理套接字消息
});
data
事件,当有消息到达时,会触发该事件,并传递消息的数据。socket.on('data', (data) => {
const message = data.toString();
console.log(`Received message: ${message}`);
});
console.log(`Received message: ${message}`);
完整的代码示例:
import * as net from 'net';
import * as readline from 'readline';
const server = net.createServer((socket) => {
console.log('Client connected');
socket.on('data', (data) => {
const message = data.toString();
console.log(`Received message: ${message}`);
});
});
const port = 3000; // 服务器端口号
server.listen(port, 'localhost', () => {
console.log(`Server listening on port ${port}`);
});
这样,当有客户端连接到服务器并发送消息时,服务器会监听消息并将其打印到控制台。
领取专属 10元无门槛券
手把手带您无忧上云