【之前就说到会整理一下H5中几个比较重要的对象和方法,今天来整理整理非常重要的Websocket,下面将会详细的介绍怎么去创建他,实现一个简单的双向通讯】
首先来了解一下我们在做网页时候通讯会用到的WebSocket:
WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。
在WebSocket API中,浏览器和服务器只需要做一个握手的动作,然后,
浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。
浏览器通过 JavaScript 向服务器发出建立 WebSocket 连接的请求,
连接建立以后,客户端和服务器端就可以通过 TCP 连接直接交换数据。
当你获取 Web Socket 连接后,你可以通过 send() 方法来向服务器发送数据,
并通过 onmessage 事件来接收服务器返回的数据。
你需要创建一下环境,前提是你已经安装了node哦,下面附上操作步骤,相信大家都可以很快学会的。
1、创建文件夹:mkdir chatapp
2、进入文件夹:cd chatapp
3、初始化:将创建你的package包,包含你的版本信息,加载器,插件等信息。npm init
4、安装express项目依赖:npm install --save express@4.15.2
5、根目录下创建你的index.js,进行依赖的模块引入,server配置等,进行实时监听
```
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');
});
```
6、运行index.js:node index.js,然后访问localhost:3000
7、根目录下创建index.html,并且引入在线的js依赖
<script src="https://cdn.bootcss.com/socket.io/2.0.3/socket.io.js"></script>
8、在index.js中发送文件到HTML,
app.get(‘/’,function(req,res){
res.sendFile(_dirname+’/index.html’);
})
9、根目录下的html中,写入你想要的页面内容,比如会话框的构建
<ul class="pages">
<li class="chat page">
<div class="chatArea">
<ul class="messages"></ul>
</div>
<input class="inputMessage" placeholder="Type here..."/>
</li>
</ul>
10、重启一下index.js查看localhost显示你写的页面
11、安装websocket的会话依赖Socket.IO:npm install --save socket.io
12、在index.js中引入io的依赖 var io = require('socket.io')(http);
13、在index.js上做io会话连接
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
14、在html中定义io后重启index.js,查看页面
15、在html中向服务器发送连接请求,用send方法向服务器发送数据,emit方法接收服务器传来的数据
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){//接收服务器传来的数据
$("#messages").append("<li>"+msg+"</li>");
});
});
16、在index.js中修改用户体验,当用户进入时给出反馈
io.on("connection",(socket) => {//有用户进入时触发
//socket代表的是每一个用户
console.log("有用户进来啦");
socket.broadcast.emit('hi欢迎进入聊天室');//只要你来,我就对你说:hi
socket.on("chat message",(msg) => {
console.log(msg);
io.emit('chat message', msg); //广播給所有的用户
})
socket.on('disconnect', function(){
console.log('用户已经离开了哦');
io.emit('chat message', "欢迎下次再来");
});
})
17、index.js中完整的代码为:
```
var app=require('express')();
var http=require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on("connection",(socket) => {//有用户进入时触发
//socket代表的是每一个用户
console.log("有用户进来啦");
socket.broadcast.emit('hi欢迎进入聊天室');//只要你来,我就对你说:hi
socket.on("chat message",(msg) => {
console.log(msg);
io.emit('chat message', msg); //广播給所有的用户
})
socket.on('disconnect', function(){
console.log('用户已经离开了哦');
io.emit('chat message', "欢迎下次再来");
});
})
http.listen(3000, function(){
console.log('listening on *:3000');
});
```
18、html中完整代码为:
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
html,body{width: 100%;height: 100%;}
body { font: 13px Helvetica, Arial; display: flex;flex-direction: column;}
form { background: #000; padding: 3px; width: 100%; height: 50px;}
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; flex: 1;overflow-y: auto;background-color:#C4E3F3;}
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
#messages li:nth-child(even) { background: #F5E79E; }
#h2{text-align: center;}
</style>
</head>
<body>
<h2 id="h2">websocket双向会话</h2>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
<script src="https://cdn.bootcss.com/socket.io/2.0.3/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){//接收服务器传来的消息
$("#messages").append("<li>"+msg+"</li>");
});
});
</script>
</html>
一个简易的通讯就这样建成了,收拾收拾东西回家,今天快累死了。
本文详细介绍如何使用WebSocket实现实时双向通讯。从环境搭建到代码实现,一步步教你如何创建WebSocket连接并实现客户端与服务器间的双向数据交换。
2042

被折叠的 条评论
为什么被折叠?



