tcp连接
需要先下载net
npm install net
客户端
const net = require('net')
const HOST = '127.0.0.1' //服务器地址
const PORT = '2000' //服务器端口
// 方式一
/* 创建tcp客户端 */
var client = net.Socket()
/* 设置连接的服务器 */
client.connect(PORT, HOST, function () {
console.log('连接成功')
/* 向服务器发送16进制的数据 */
setTnterval(()=>{
client.write(new Buffer.from([0x00,0x05]))
},1000)
/* 监听服务器传来的data数据 */
client.on("data",function (data) {
console.log(JSON.stringify(data))
})
/* 监听end事件 */
client.on("end",function () {
console.log("end")
})
/* 监听error事件 */
client.on("error",function () {
console.log("error")
})
})
// 方式二
const clientSocket = net.createConnection(PORT, HOST, function () {
console.log('连接成功')
/* 向服务器发送16进制的数据 */
setTnterval(()=>{
client.write(new Buffer.from([0x00,0x05]))
},1000)
})
/* 监听服务器传来的data数据 */
clientSocket .on("data",function (data) {
console.log(JSON.stringify(data))
})
/* 监听end事件 */
clientSocket .on("end",function () {
console.log("end")
})
/* 监听error事件 */
clientSocket .on("error",function () {
console.log("error")
})
udp连接
需要先下载dgram
npm install dgram
客户端
const dgram = require("dgram")
/* 创建udp客户端 */
const socket = dgram.createSocket("udp4")
socket.removeAllListeners()
/* 开启成功 */
socket.on('listening', function () {
/* 接收数据 */
socket.on("message", function (msg,rinfo) {
console.log(JSON.stringfy(msg))
})
})
/* 监听指定地址以及端口 */
socket.bind(9000,'127.0.0.1')
websocket连接
需要下载ws
npm install ws
客户端
const wsclient = require('ws')
/* 连接websocket服务器 */
let wss = net wsclient("ws://127.0.0.1")
wss.onopen = function (e) {
console.log("连接成功")
/* 发送数据 */
wss.send('websocket发送的数据')
/* 接收数据 */
wss.onmessage = function (e) {
console.log(e)
}
}
wss.onclose = function () {
console.log("服务器关闭")
}
wss.onerror = function () {
console.log("连接出错")
}