客戶端須要引用socket.io.js文件 服務端須要按照node環境,以及npm install socket.io用來安裝服務端的socket.io
一個大神掛的cdn。javascript
<script src="http://realtime.plhwin.com/socket.io/socket.io.js"></script>
<script src="/socket.io/socket.io.js"></script>
function send(){ var socket = io('ws://localhost:8888'); socket.emit('listmessage',{ sid :'13947965133'}); }
var app = require('http').createServer(handler) var io = require('socket.io')(app); var fs = require('fs'); app.listen(8888); function handler (req, res) { fs.readFile(__dirname + '/index.html', function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading index.html'); } res.writeHead(200); res.end(data); }); } //核心代碼 io.on('connection', function (socket) { socket.on('listmessage', function (data) { console.log(data); }); }); //核心代碼
代碼詳見 https://github.com/13947965133/imnugd/tree/master/websocket/socketio_testhtml
function SendToClientB(){ var socket = io('ws://localhost:8888'); socket.emit('listmessage',{ sid :'13947965133',message:"I am is message!"}); }
function ReadFromClientA(){ var socket = io('ws://localhost:8888'); socket.on('sid_13947965133', function (data) { console.log(data); }); }
io.on('connection', function (socket) { socket.emit('news', { hello2: 'worldwww',guohan:'values' }); socket.on('listmessage', function (data) { if (data.sid = '13947965133') { io.emit('sid_13947965133',data); console.log(data); }else{ console.log("no find match user"); } }); });