WebSocket 是基于http 协议的实时通信的协议,浏览器可以主动给服务器发送请求,而浏览器也可以给服务器发送请求。HTML 5 的出现在js 上添加了websocket 的api 。
websocket 和 http 的区别
在做一个web聊天系统时,可能有的人使用http 协议制作,使用的方案大部分都是每秒去刷新消息。来获取最新的消息,然后呈现给各各用户。
这样的缺点显而易见,当没有最新消息时时候,那些刷新消息的访问,无疑是给服务器增加了负担。
而websocket 正是处理这些即时通讯的系统而出现的。
当websocket 一旦和服务端建立连接后,浏览器不用再次访问服务端,服务端可以主动的请求浏览器。
下图是模仿websocket 聊天室,服务器又4个浏览器已有连接,当接受但一个浏览器的消息后,服务器就会将接收到的消息发送给这个4个浏览器。
javascript aip
var socketEvent = {
'open':function(e){
console.log('open');
},
'message':function(e){
console.log(e.data);
},
'error':function(e){
console.log('error');
},
'close':function(e){
console.log('close');
},
};
var socket = new WebSocket('ws://localhost:8080/Test');
socket.onopen = socketEvent.open;
socket.onmessage = socketEvent.message;
socket.onerror = socketEvent.error;
socket.onclose = socketEvent.close;
socket.send('hello websocket');
new WebSocket('ws://localhost:8080/chat')
创建一个websocket 对象
socket.onopen
当websocket 打开时调用
socket.onmessage
当websocket 接收到数据调用
socket.onerror
当websocket 出错时调用
socket.onclose
当websocket 关闭调用
socket.send('hello websocket')
向后台发送数据
tomcat websocket服务端
@ServerEndpoint("/Test")
public class TestWebSocket {
/**
* 与客户端的会话
*/
private Session session;
/**
* 当有浏览器连接时
* @param session
*/
@OnOpen
public void onOpen(Session session){
this.session = session;
}
/**
* 接收浏览器发送的数据
* @param msg 消息内容
*/
@OnMessage
public void onMessage(String msg){
try {
session.getBasicRemote().sendText("back"+msg);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 当连接出错时
* @param t
*/
@OnError
public void onError(Throwable t){
System.out.println(t.getMessage());
}
/**
* 当连接关闭时
*/
@OnClose
public void onClose(){
System.out.println("websocket close.");
}
}