一、HTTP的历史
早在HTTP建立之初,主要就是为了将超文本标记语言(HTML)文档从Web服务器传送到客户端的浏览器。但是到了WEB2.0以来,我们的页面变得复杂,有了CSS,Javascript,来丰富我们的页面展示,当ajax的出现,我们又多了一种向服务器端获取数据的方法,这些都是基于HTTP协议的。同样到了移动互联网时代,我们页面可以跑在手机端浏览器里面,但是和PC相比,手机端的网络情况更加复杂,这使得我们开始了不得不对HTTP进行深入理解并不断优化过程中。
二、影响一个HTTP网络请求的因素
影响一个HTTP网络请求的因素主要有两个:带宽和延迟。
(1)带宽
如果说我们还停留在拨号上网的阶段,带宽可能会成为一个比较严重影响请求的问题,但是现在网络基础建设已经使得带宽得到极大的提升,我们不再会担心由带宽而影响网速,那么就只剩下延迟了。
(2)延迟
- 浏览器阻塞(HOL blocking):浏览器会因为一些原因阻塞请求。浏览器对于同一个域名,同时只能有 4 个连接(这个根据浏览器内核不同可能会有所差异),超过浏览器最大连接数限制,后续请求就会被阻塞。
- DNS 查询(DNS Lookup):浏览器需要知道目标服务器的 IP 才能建立连接。将域名解析为 IP 的这个系统就是 DNS。这个通常可以利用DNS缓存结果来达到减少这个时间的目的。
- 建立连接(Initial connection):HTTP 是基于 TCP 协议的,浏览器最快也要在第三次握手时才能捎带 HTTP 请求报文,达到真正的建立连接,但是这些连接无法复用会导致每次请求都经历三次握手和慢启动。三次握手在高延迟的场景下影响较明显,慢启动则对文件类大请求影响较大。
三、HTTP1.0与HTTP1.1的一些区别
HTTP 1.0基于请求和应答模式,也就是服务器不能主动给客户端推送消息;而HTTP 1.1相对于HTTP 1.0有了一些进步,1.0 建立一次连接,只能发送一次请求,而1.1修改了connection: keep-alive, 支持长连接(PersistentConnection)和请求的流水线(Pipelining)处理,在一个TCP连接上可以传送多个HTTP请求和响应,减少了建立和关闭连接的消耗和延迟,在HTTP1.1中默认开启Connection: keep-alive,一定程度上弥补了HTTP1.0每次请求都要创建连接的缺点,此时request=response。
四、WebSocket
webSocket 是一个持久化的双向通信协议,webSocket 是基于HTTP协议的,或者说 借用 HTTP的协议来完成一部分握手。建立在TCP之上,同http一样通过TCP来传输数据,但是它和http最大的不同有两点:
- WebSocket是一种双向通信协议,在建立连接后,WebSocket服务器和Browser/UA都能主动的向对方发送或接收数据,就像 Socket一样,不同的是WebSocket是一种建立在Web基础上的一种简单模拟Socket的协议;
- WebSocket需要通过握手连接,类 似于TCP它也需要客户端和服务器端进行握手连接,连接成功后才能相互通信。
websocket的连接建立过程主要有三步:第一步是客户端发送GET 请求, upgrade,第二步是服务器给客户端 switching protocol,最后第三步就进行了webSocket的通信了。
1、发送一个GET请求
2、服务器收到了协议,返回一个 Switching Protocol, 这样就连接成功了
3、Browser收到服务器回复的数据包后,如果数据包内容、格式都没有问题的话,就表 示本次连接成功,触发onopen消息,此时Web开发者就可以在此时通过send接口想服务器发送数据。否则,握手连接失败,Web应用程序会收到 onerror消息,并且能知道连接失败的原因。接下来的通信都是websocket, 这样就很好的连接了。
4. WebSocket实操
- HTML页面
<!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:12345/websocket/12345';
var websocket;
var i = 0;
if (window.WebSocket) {
websocket = new WebSocket(wsurl);
//连接建立
websocket.onopen = function (evevt) {
console.log("Connected to WebSocket server.");
$('.show-area').append('<p class="bg-info message"><i class="glyphicon glyphicon-info-sign"></i>Connected to WebSocket server!</p>');
}
//收到消息
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>
- Java代码 - 引入starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- Java代码 - 添加webSocketConfig配置类
/**
* 开启WebSocket支持
**/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
- Java代码 - 添加webSocketServer服务端类
import java.io.IOException;
import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.example.util.WebSocketUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
@ServerEndpoint("/websocket/{pageId}")
@Component
@Slf4j
@Data
public class WebSocketServer {
private Session session;
private String pageId="";
private long timestamp=0;
private boolean isSend;
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session,@PathParam("pageId") String pageId) {
this.session = session;
this.pageId = pageId;
this.timestamp = System.currentTimeMillis();
this.isSend=false;
log.info("--websocket pageId:"+pageId);
log.info("--websocket session:"+session);
WebSocketUtil.webSocketMap.putIfAbsent(pageId, this);
log.info("websocket open connect");
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(@PathParam("pageId")String pageId) {
WebSocketUtil.webSocketMap.remove(pageId);
log.info("websocket close");
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
if(StringUtils.isNotBlank(message)){
try {
sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("error");
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 实现服务器主动推送,推送Object消息
* @throws EncodeException
*/
public static void sendObjectMessage(Session session,Object message) {
try {
session.getBasicRemote().sendObject(message);
} catch (IOException | EncodeException e) {
e.printStackTrace();
}
}
}
- Java代码 - 添加WebSocketUtil,保存webSocket连接
import com.example.bean.WebSocketServer;
import java.util.concurrent.ConcurrentHashMap;
public class WebSocketUtil {
public static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
}
- Java代码 - 启动定时任务
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import com.example.util.WebSocketUtil;
@Slf4j
@Component
@EnableScheduling
public class WebsocketSchedule {
@Scheduled(cron = "0/1 * * * * ?") //每2分钟执行一次
private void webSocketPush(){ //超时的没有返回的,超过1分钟则返回错误
ConcurrentHashMap<String, WebSocketServer> socketMap = WebSocketUtil.webSocketMap;
if(socketMap != null){
socketMap.forEach((key, value) -> {
long addTimeStame = value.getTimestamp();
long nowTimeStame = System.currentTimeMillis();
if(nowTimeStame - addTimeStame > 30000 ){
if(!value.isSend()){
try {
value.setSend(true);
log.info("---is send :" + value.isSend());
value.setTimestamp(System.currentTimeMillis());
value.sendMessage("request fail!");
} catch (IOException e) {
e.printStackTrace();
log.error("error",e);
}
}
}
});
}
}
}
五、HTTP与WebSocket的区别
HTTP 1.1 与HTTP 1.0 之间的区别可以通过请求头 Connection: keep-alive 来区别,把多个 HTTP 请求合并为一个,但是 Websocket 其实是一个新协议,跟 HTTP 协议基本没有关系,只是为了兼容现有浏览器,所以在握手阶段使用了 HTTP 。
WebSocket 建立在 TCP 协议之上,与 HTTP 协议有着良好的兼容性,默认端口也是80和443,并且握手阶段采用 HTTP 协议,因此握手时不容易屏蔽,能通过各种 HTTP 代理服务器,数据格式比较轻量,可以发送文本,也可以发送二进制数据,性能开销小,通信高效,也没有同源限制,客户端可以与任意服务器通信。