连接服务
当客户端成功加载socket.io客户端文件后会获取到一个全局对象io,我们将通过io.connect函数来向服务端发起连接请求。
var socket = io.connect('/');
socket.on('connect',function(){
//连接成功
});
socket.on('disconnect',function(data){
//连接断开
});
connect函数可以接受一个url参数,url可以socket服务的http完整地址,也可以是相对路径,如果省略则表示默认连接当前路径。与服务端类似,客户端也需要注册相应的事件来捕获信息,不同的是客户端连接成功的事件是connect。
了解了客户端如何使用,下面我们创建网页index.html,并添加如下内容(保存):
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script>
window.onload = function(){
var socket = io.connect('/');
socket.on('connect',function(){
document.write('连接成功!');
});
};
</script>
</head>
<body>
</body>
</html>
页面添加完毕还要记得在服务端app.js中为它添加路由,让我们可以访问测试网页:
app.get('/index',function(req,res){
res.sendFile('index.html',{root:__dirname});
});
1、添加网页index.html,编辑代码连接socket服务。
2、在服务端添加路由,通过/index可以访问到index.html页面。