最近一个朋友在项目中需要实现实时聊天等一些功能,帮忙弄了个粗略的,上代码。
服务器端
安装 express 跟 socket.io
npm install --save express
npm install --save socket.io
var app = require(‘express‘)(); var http = require(‘http‘).Server(app); var io = require(‘socket.io‘)(http); app.get(‘/‘, function(req, res){ res.send(‘<h1>Welcome Realtime Server</h1>‘); }); io.on("connection",function(socket){ console.log("a user connected"); socket.on("disconnect",function(){ console.log("a user disconnect"); io.emit("dis",{ user_id : socket.name }); }); socket.on("join",function(data){ var userid = data.userid; socket.name = userid; io.emit("joinok",{ msg : "join ok", userid : userid }); }); socket.on("xiaoxi",function(data){ io.emit("message",data); }); }); http.listen(1000, function(){ console.log(‘listening on *:1000‘); });
客户端
引入socket.io
// 连接服务器 var socket = io.connect(server_add); socket.emit("join",{ userid : user_id }); socket.on("joinok",function(data){ rtop.append(‘<p>‘+data.userid+‘加入聊天室</p>‘); }); function sendfn(){ var val = $.trim(text.val()); if(val == "") return alert("请输入"); socket.emit("xiaoxi",{ user_id : user_id, msg : val }); } socket.on("message",function(data){ rtop.append(‘<p>‘+data.user_id+‘说: ‘+data.msg+‘</p>‘); if(data.user_id == user_id) text.val(""); }); socket.on("dis",function(data){ rtop.append(‘<p>‘+data.user_id+‘离开</p>‘); });
时间: 2024-11-11 10:37:08