c 语言socket双向通信,Node.js socket 双向通信

使用场景:  聊天室;大量数据常驻交互;

技术栈: Node.js,     Vue.js || 原生JS

服务端代码:

const app = require('http').createServer()

const io= require('socket.io')(app)

app.listen(8877)

io.on('connection', scoket =>{

let i= 1const t= setInterval(()=>{

i++

if(i >= 12) {

clearInterval(t)

}//服务端往客户端发送消息

scoket.emit('news', { hello: 'world', t: newDate().getTime() })

},1000)//服务端监听客户端的消息

scoket.on('receiveEvent', data =>{

console.log('receiveEvent: ', data)

})

})

客户端代码:

-- Vue 例子:

scoket:

{{item}}

beforeMount() {//初始化 客户端 socket

this.socket = io('http://localhost:8877')

},

data() {return{

arr: []

}

},

mounted() {//监听服务端 scoket 'news' 数据流

this.socket.on('news', data =>{this.arr.push(data)

})

},

methods: {//客户端往服务端发送消息

clientToServer() {this.socket.emit('receiveEvent', 'Hi~ im from clientSide')

}

},//销毁 socket

beforeDestroy() {this.socket.close('news')

}

}

-- 原生代码示例:

Socket Demo

Send Msg

window.οnlοad= () =>{

const socket=io.connect(wsUrl);//监听服务端消息

socket.on("news", data =>{

console.log("news: ", data);

});//往服务端发送消息

document.getElementsByTagName('button')[0].onclick = function() {

socket.emit('receiveEvent', 'msg from client!')

}

};

后话(备注):

这里是使用的 Node.js  socket.io 第三方库, 笔者尝试过 pm2 集群部署后, 因为多核心运行的特点, 导致socket会话的id出现错误, 一直没处理好, 如有大神做过类似处理, 请交流指教!!!

原文出处:https://www.cnblogs.com/qq4535292/p/11227444.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值