引入net模块
net 模块提供了异步的网络 API,用于创建基于流的 TCP 或 IPC 服务器 (net.createServer()) 和客户端 (net.createConnection())。文章来源地址https://www.toymoban.com/news/detail-601600.html
let net = require('net');
服务端
let net = require('net');
let server = net.createServer(socket => {
socket.on('data', data =>{
console.log('server recv data:', data);
})
socket.on('close', function(hadError) {
console.log(`sock close hadError: "${hadError}"`);
})
socket.on('end', function() {
console.log('sock end');
})
socket.on('error', function(err) {
console.log('sock err:', err);
})
// 设置最大连接数
server.maxConnections = 100;
// 获取连接数
server.getConnections((err, count) => {
console.log('server count:', count);
})
});
server.listen(10033, () => {
console.log("server is running on 10033");
})
server.on('error', function(err) {
console.log("server err:", err);
})
server.on('close', () => {
console.log("server closed")
})
客户端
let net = require('net');
let client = net.Socket();
const host = '127.0.0.1';
client.connect(10033, host, () => {
console.log('connect the server');
client.write('send first data');
});
client.on('data', data => {
console.log('client data:', data);
})
client.on('end', () => {
console.log('client end');
})
client.on('error', (err) => {
console.log(`client error: ${err}`);
});
文章来源:https://www.toymoban.com/news/detail-601600.html
到了这里,关于JavaScript实现tcp客户端和服务端的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!