nodejs与websocket的库socket.io的应用

最近nodejs,html5 ,websocket等前端新技术越来越流行,特别是nodejs,让js做了服务器端的事情。下面进入今天的正题, 一般网页都无法做真正的实时通讯。比如说新浪微博的提醒,私信等功能,看上去是实时的,其实不然,它是用的轮训,有一定的延迟时间。而我接下来要说的websocket,正是为了解决这个问题。

话不多说,贴上代码:

服务器端 server.js,采用了nodejs:

var http = require('http'),
io = require('socket.io');
var server = http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.write('<br /><h1>nodejs</h1><p>');
res.end('hello world');
}).listen(3000);

var socket = io.listen(server);
socket.on('connection',function(client){
//给客户端发送news事件
client.emit('news', { hello: 'world' });
//注册test事件,来响应客户端的请求
client.on('test', function (data) {
console.log(data);
});
});

console.log('my first nodejs');


下面是客户端:

<html>
<head>

<br />
<style type="text/css">
#io_0,#io_1,#io_2 {background: blue; color: white; padding: 5px; }
#io_3,#io_4,#io_5 {background: green; color: white; padding: 5px; }
#io_6,#io_7,#io_8 {background: red; color: white; padding: 5px; }
#io_9,#io_10 {background: blue; color: white; padding: 5px; }
#io_11,#io_12,#io_13,#io_14 {background: green; color: white; padding: 5px; }
.red{background:red; color:white; padding: 5px;}
.blue{background:blue; color:white; padding:5px;}
.green{background:green; color:white; padding:5px;}
#support{
	font-size:15pt;
	padding:10px;
	border:3px #666 solid;
}
</style>
<p>
<!-- http://127.0.0.1:3000/socket.io/socket.io.js  	注意这里,socket.io/socket.io.js是==动态生成==的, 	http://127.0.0.1:3000 是你服务器的地址, 	路径不要改变,不然会提示找不到socket.io.js -->
<script src="http://127.0.0.1:3000/socket.io/socket.io.js"></script>
</head>
<script>
var socket = io.connect('http://127.0.0.1:3000');

//注册news 事件
socket.on('news', function (data) {
	console.log(data);
	//给服务器端发送事件test,(服务器端已经注册过test事件了)
	socket.emit('test', { my: 'data' });
});

// if ('WebSocket' in window) {
// 	var socket = new WebSocket('ws://127.0.0.1:3000');
// 	socket.onopen = function(event){
// 		socket.emit('test', { my: 'data' });
// 		socket.send("sdfslfsdf");
// 	};
// 	console.log(1);
// }else{
// 	console.log(0);
// }
</script>
<body>

<br />
<div id="main">
<br />
<table width="480">
<br />
<thead id="iohead"></thead>
<p>
<br />
<tbody id="iobody"></tbody>
<p>
	    </table>
<p>
<br />
<form name="messageForm" id="messageForm" method="get" action="">
	        <input size="50" type="text" id="message" value="Hello" ><button id="buttonSend">Send</button>
	    </form>
<p>
	</div>
<p>
</body>
</html>

运行结果如下:


本文出自:http://www.yinchuandong.com/?p=64  ,这也是我自己写的



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值