WebSocket协议概述
WebSocket是一种在单个TCP连接上进行全双工通信的协议,允许服务端主动的向客户端推送消息,使得服务端和客户端之间数据的传输变得简单。对于WebSocket协议的连接,只需要通过一次基于HTTP/1.1 协议的101状态码进行握手即可建立连接,并且这种连接是持久的。
简单聊天室实例
客户端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
textarea{
resize: none;
}
#ChatPage{
text-align: center;
position: relative;
left: 30%;
top: 60px;
}
</style>
</head>
<body background="img/bg.jpg">
<div id="ChatPage" style="width: 500px;height: 600px; border: solid;background-color: darkgray; opacity: 0.6;">
<div style="height: 5%;width: 100%;margin-top: 10px;">
用户名:<input type="text" name="username" id="username" value=""/>
发送往:<input type="text" name="target" id="target" value=""/>
</div>
<div style="width: 100%;height: 63%;border-top: solid;">
<ul id="cord" style="width: 92%;height: 100%;list-style-type: none;overflow: scroll; text-align: start;" >
</ul>
</div>
<div style=