什么是websocket
Websocket是应用层第七层上的一个应用层协议,WebSocket 的最大特点就是,服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息,是真正的双向平等对话。
HTTP 有 1.1 和 1.0 之说,也就是所谓的 keep-alive ,把多个 HTTP 请求合并为一个,但是 Websocket 其实是一个新协议,跟 HTTP 协议基本没有关系,只是为了兼容现有浏览器,所以使用了 HTTP 。
客户端首先会向服务端发送一个 HTTP 请求,包含一个 Upgrade 请求头来告知服务端客户端想要建立一个 WebSocket 连接
WebSocket 的其他特点:
- 建立在 TCP 协议之上,服务器端的实现比较容易。
- 与 HTTP 协议有着良好的兼容性。默认端口也是80和443,并且握手阶段采用 HTTP 协议,因此握手时不容易屏蔽,能通过各种 HTTP 代理服务器。
- 数据格式比较轻量,性能开销小,通信高效。
- 可以发送文本,也可以发送二进制数据。
- 没有同源限制,客户端可以与任意服务器通信。
- 协议标识符是ws(如果加密,则为wss),服务器网址就是 URL。
- 简易聊天使用:
<!DOCTYPE html>
<html>
<head>
<title>简易聊天Demo</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, user-scalable=no">
<link href="https://cdn.bootcss.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<style type="text/css">
html, body {
min-height: 100%;
}
body {
margin: 0;
padding: 0;
width: 100%;
font-family: "Microsoft Yahei", sans-serif, Arial;
}
.container {
text-align: center;
}
.title {
font-size: 16px;
color: rgba(0, 0, 0, 0.3);
position: fixed;
line-height: 30px;
height: 30px;
left: 0px;
right: 0px;
background-color: white;
}
.content {
background-color: #f1f1f1;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
margin-top: 30px;
}
.content .show-area {
text-align: left;
padding-top: 8px;
padding-bottom: 168px;
}
.content .show-area .message {
width: 70%;
padding: 5px;
word-wrap: break-word;
word-break: normal;
}
.content .write-area {
position: fixed;
bottom: 0px;
right: 0px;
left: 0px;
background-color: #f1f1f1;
z-index: 10;
width: 100%;
height: 160px;
border-top: 1px solid #d8d8d8;
}
.content .write-area .send {
position: relative;
top: -28px;
height: 28px;
border-top-left-radius: 55px;
border-top-right-radius: 55px;
}
.content .write-area #name {
position: relative;
top: -20px;
line-height: 28px;
font-size: 13px;
}
</style>
</head>
<body>
<div class="container">
<div class="title">简易聊天demo</div>
<div class="content">
<div class="show-area"></div>
<div class="write-area">
<div>
<button class="btn btn-default send">发送</button>
</div>
<div><input name="name" id="name" type="text" placeholder="input your name"></div>
<div>
<textarea name="message" id="message" cols="38" rows="4" placeholder="input your message..."></textarea>
</div>
</div>
</div>
</div>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script>
$(function () {
// var wsurl = 'ws://127.0.0.1:3000';
var websocket;
var i = 0;
if (window.WebSocket) {
// 原生js就支持的
// WebSocket 建立链接后 就不会在断 相当于打电话 只要不挂断就一直可以通讯
// 1 前端必须按照步骤写上链接WebSocket 2 后台也需要对应链接上WebSocket
// 对应我们来说 有人封装了 一个 sockect.io 他就是封装 WebSocket
// 1 new WebSocket
websocket = new WebSocket('ws://127.0.0.1:3000');
//2 连接建立 websocket.onopen
websocket.onopen = function (evevt) {
console.log("WebSocket 链接上了");
$('.show-area').append('<p class="bg-info message"><i class="glyphicon glyphicon-info-sign"></i>Connected to WebSocket server!</p>');
}
//3 收到后台发来消息就会执行 websocket.onmessage
websocket.onmessage = function (event) {
// 在这里就 解析判断 后台返回什么数据 对应操作
var msg = JSON.parse(event.data); //解析收到的json消息数据
var type = msg.type; // 消息类型
var umsg = msg.message; //消息文本
var uname = msg.name; //发送人
i++;
if (type == 'usermsg') {
$('.show-area').append('<p class="bg-success message"><i class="glyphicon glyphicon-user"></i><a name="' + i + '"></a><span class="label label-primary">' + uname + ' : </span>' + umsg + '</p>');
}
if (type == 'system') {
$('.show-area').append('<p class="bg-warning message"><a name="' + i + '"></a><i class="glyphicon glyphicon-info-sign"></i>' + umsg + '</p>');
}
$('#message').val('');
window.location.hash = '#' + i;
}
//发生错误 链接出错
websocket.onerror = function (event) {
i++;
console.log("Connected to WebSocket server error");
$('.show-area').append('<p class="bg-danger message"><a name="' + i + '"></a><i class="glyphicon glyphicon-info-sign"></i>Connect to WebSocket server error.</p>');
window.location.hash = '#' + i;
}
//连接关闭 关闭链接
websocket.onclose = function (event) {
i++;
console.log('websocket Connection Closed. ');
$('.show-area').append('<p class="bg-warning message"><a name="' + i + '"></a><i class="glyphicon glyphicon-info-sign"></i>websocket Connection Closed.</p>');
window.location.hash = '#' + i;
}
function send() {
var name = $('#name').val();
var message = $('#message').val();
if (!name) {
alert('请输入用户名!');
return false;
}
if (!message) {
alert('发送消息不能为空!');
return false;
}
var msg = {
message: message,
name: name
};
try {
websocket.send(JSON.stringify(msg));
} catch (ex) {
console.log(ex);
}
}
//按下enter键发送消息
$(window).keydown(function (event) {
if (event.keyCode == 13) {
console.log('user enter');
send();
}
});
//点发送按钮发送消息
$('.send').bind('click', function () {
send();
});
}
else {
alert('该浏览器不支持web socket');
}
});
</script>
</body>
</html>