socket.io 记
var express = require('express'); var path = require('path'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); app.use(express.static(path.join(__dirname,'/public'))); io.on('connection', function(socket){ console.log('a user connected'); socket.on('msg', function(data){ console.log(data); socket.broadcast.emit('new msg', data); }); socket.on('disconnect',function(){ console.log('user disconnet'); }); }); http.listen(3000, function(){ console.log('listening on 3000'); });
前端
<!DOCTYPE html> <html> <head> <title>sk</title> </head> <script src="https://cdn.bootcss.com/socket.io/1.7.3/socket.io.js"></script> <script src="https://code.jquery.com/jquery-1.11.1.js"></script> <body> test<br/> <div id="content"></div> <input type="text" id="msg"> <input type="button" id="send_btn" value="Send" > </body> <script> window.onload=function(){ var socket = io.connect('http://127.0.0.1:3000'); socket.on('new msg', function(data){ console.log('<<'+data); $('#content').html($('#content').html()+'<br/>'+ data); }); console.log("-------------"); $('#send_btn').click(function(){ socket.emit('msg', $('#msg').val()); $('#msg').val(''); return false; }); } </script> </html>
本文出自 码农,转载时请注明出处及相应链接。
发表评论