Socket.io实际上是WebSocket的父集,Socket.io封装了WebSocket和轮询等方法
首先得在你的项目中安装socket.io
$ npm install socket.io
服务端代码:
var app=require(‘http‘).createServer() var io=require(‘socket.io‘)(app) var PORT =5555; var clientCount=0; app.listen(PORT) io.on(‘connection‘,function(socket){ clientCount++ socket.nickname=‘user‘+clientCount io.emit(‘enter‘,socket.nickname+‘ comes in‘) socket.on(‘message‘,function(str){ io.emit(‘message‘,socket.nickname+‘ says: ‘+str) }) socket.on(‘disconnect‘,function(){ io.emit(‘leave‘,socket.nickname+‘ left‘) }) })
客户端代码:
<!DOCTYPE html> <html> <head> <mate charset=‘utf-8‘ /> <title>websocket</title> <script src="socket.io.js"></script> </head> <body> <h1>chat room</h1> <input type="text" id=‘sendtxt‘ /> <button id=‘sendbtn‘>发送</button> <div id="recv"></div> <script type="text/javascript"> var socket=io("ws://localhost:5555/"); function showMessage(str,type){ var div=document.createElement(‘div‘); div.innerHTML=str; if(type==‘enter‘){ div.style.color=‘blue‘; }else if(type==‘leave‘){ div.style.color=‘red‘ } document.body.appendChild(div); } document.getElementById(‘sendbtn‘).onclick=function(){ var txt=document.getElementById("sendtxt").value; if(txt){ socket.emit(‘message‘,txt); } } socket.on(‘enter‘,function(data){ showMessage(data,‘enter‘) }) socket.on(‘message‘,function(data){ showMessage(data,‘message‘) }) socket.on(‘leave‘,function(data){ showMessage(data,‘leave‘) }) </script> </body> </html>
来自慕课网课程:
https://www.imooc.com/learn/861
原文地址:https://www.cnblogs.com/qiufang/p/8610438.html
时间: 2024-11-09 02:46:17