您可以使用 Node.js 核心 API 附带的 Net Module 创建 TCP 套接字服务器或作为客户端连接到现有的 TCP 服务器。
如果您想创建一个新的 TCP 服务器,您可以使用 net.createServer() 或自己创建一个 new Server。
const {Server} = require('net')
const server = new Server(socket=> {
console.log('client connected')
// Attach listeners for the socket
socket.on('data', message => {
console.log('message')
// Write back to the client
socket.write('world')
})
// Send the client a message to disconnect from the server after a minute
setTimeout(() => socket.write('disconnect'), 60000)
socket.on('end', () => console.log('client disconnected'))
})
server.listen('localhost', () => console.log('listening'))
如果您希望创建与现有服务器的客户端 TCP 连接,您可以使用 net.createConnection() 或创建 new Socket 并使用 socket.connect() 连接到 TCP 服务器。
const {Socket} = require('net')
const client= new Socket()
client.connect('localhost', () => {
console.log('connected to localhost')
client.on('data', message => {
if (message === 'disconnect') {
console.log('disconnecting from localhost')
client.end()
} else {
console.log(`Message from the Server: ${message}`)
}
})
client.write('hello!')
})