socket.io实现websocket聊天室

现在很流行的websocket的实现socket.io同样包括客户端和服务器端两部分。它不仅简化了接口,使得操作更容易,而且对于那些不支持WebSocket的浏览器,会自动降为Ajax连接,最大限度地保证了兼容性。它的目标是统一通信机制,使得所有浏览器和移动设备都可以进行实时通信。
首先我们需要保证设备已经安装了node.js,我们后续的开发工作都在node环境中执行,如果没安装请点击这里Node.JS;
然后我们就可以开始编写程序了:

  1. 新建package.json,里面包含了我们开发中所用到的依赖
{
   
  "name": "socket-chat-example",
  "version": "0.0.1",
  "description": "my first socket.io app",
  "dependencies": {
   }
}
  1. 结合express框架进行编写,我们用npm install --save,以便可以方便加到我们的dependencies中;
 npm install --save express
  1. 现在我们可以编写index.js文件
var app = require('express')();
var http = require('http').Server(app);

app.get('/', function(req, res){
   
  res.send('<h1>Hello world</h1>');
});

http.listen(3000, function(){
   
  console.log('listening on *:3000');
});

这转化为以下内容:

  • Express初始化app为可以提供给HTTP服务器的函数处理程序(如第2行所示)。
  • 我们定义一个路由处理程序/,当我们访问我们的网站时,它会被调用
  • 我们使http服务器侦听端口3000。
    If you run node index.js you should see the following:

A console saying that the server has started listening on port 3000

And if you point your browser to http://localhost:3000:

A browser displaying a big 'Hello World'

提供HTML

到目前为止,index.js我们正在调用res.send并传递一个HTML字符串。如果我们将整个应用程序的HTML放在那里,我们的代码看起来会很混乱。相反,我们将创建一个index.html文件并提供服务。

让我们重构我们的路由处理程序来sendFile代替:

app.get'/'function(req,res) {
    
  res.sendFile(__ dirname + '/ index.html'; 
};

并填充index.html以下内容:

<!doctype html>
<html>
  <head>
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值