nodejs连接tcp、udp、websocket服务器

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("连接出错")
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值