|
|
用socket.io实现WebSocket的一个简单例子
客户端代码:
<html><head> <title></title> <script src="../js/socket.io.client.js"></script> <script type="text/javascript"> function doit() { var socket = io.connect('http://localhost'); socket.on('news', function (data) {//接收到服务器发送过来的名为'new'的数据 console.log(data.hello);//data为应服务器发送过来的数据。 socket.emit('my new event', { my:'new data' });//向服务器发送数据,实现双向数据传输 }); socket.on('other', function (data) {//接收另一个名为'other'数据, console.log(data.hello); socket.emit('event1', { my:'other data' }); }); } </script></head><body><button id='btn' >click me</button></body></html>
在chrome,Crtl+Shift+j打开终端,可看到输出结果。
socket.io.client.js可以https://github.com/LearnBoost/socket.io-client下载到本地,在<script src="..">指向本机的js库。
服务器用nodejs实现
代码
var http= require('http'), io= require('socket.io'), express= require('express');var app = express.createServer(), io = io.listen(app);app.listen(80);io.sockets.on('connection', function (socket) { socket.emit('news', { hello: 'world' });//监听,一旦客户端连接上,即发送数据,第一个参数'new'为数据名,第二个参数既为数据 socket.on('my other event', function (data) {//捕获客户端发送名为'my other event'的数据 console.log(data.my); }); socket.emit('other', { hello: 'other world' });//发送另一个数据 socket.on('evnet1', function (data) {//捕获另外一个数据 console.log(data.my); });});
测试结果,客户端可正常显示
<div class="quote_title">引用 |
|