当前位置: 移动技术网 > 网络运营>服务器>tomcat > 详解Tomcat7中WebSocket初探

详解Tomcat7中WebSocket初探

2019年05月28日  | 移动技术网网络运营  | 我要评论
html5中定义了websocket规范,该规范使得能够实现在浏览器端和服务器端通过websocket协议进行双向通信。 在web应用中一个常见的场景是server端

html5中定义了websocket规范,该规范使得能够实现在浏览器端和服务器端通过websocket协议进行双向通信。

在web应用中一个常见的场景是server端向client端推送某些消息,要实现这项功能,按照传统的思路可以有以下可选方案:

  • ajax + 轮询 :这种方案仅仅是一个模拟实现,本质还是http请求响应的模式,由于无法预期什么时候推送消息,造成很多无效的请求;
  • 通过 flash等第三方插件 :这种方式能够实现双向通信,但有一个前提条件就是依赖第三方插件,而在移动端浏览器大多数都不支持flash.

随着html5技术的普及,主流浏览器对html5标准的支持越来越好,利用浏览器原生支持websocket就可以轻松的实现上面的功能。只需要在浏览器端和服务器端建立一条websocket连接,就可以进行双向同时传递数据。相比于传统的方式,使用websocket的优点显而易见了:

  • 主动的双向通信模式:相对于使用ajax的被动的请求响应模式,主动模式下可以节省很多无意义的请求;
  • 浏览器原生支持:简化了编程环境和用户环境,不依赖第三方插件;
  • 高效省流量:以数据帧的方式进行传输,抛弃了http协议中请求头,直接了当.

那么在实际中如何建立websocket连接?在浏览器端和服务器端如何针对websocket编程?

就此问题,下文描述了建立websocket连接的过程,浏览器端websocket接口,并以tomcat 7 为例在服务器端编写websocket服务。

1. 建立websocket连接过程

关于websocket规范和协议参考

设计websocket协议的一个重要原则就是能和现有的web方式和谐共处,建立websocket连接是以http请求响应为基础的,这个过程为 websocket握手 .

图下所示为一个websocket建立连接的请求和响应过程:

此处稍作解释一下:

  1. 浏览器向服务器发送一个 upgrade 请求头,告诉服务器 “我想从 http 协议 切换到 websocket 协议”;
  2. 服务器端收到请求,如果支持 websocket ,则返回pupgrade响应头,表示“我支持websocket协议,可以切换”;
  3. 浏览器接收响应头,从原来的http协议切换websocket协议,websocket连接建立起来.

websocket连接建立在原来http所使用的tcp/ip通道和端口之上 ,也就是说原来使用的是8080端口,现在还是使用8080端口,而不是使用新的tcp/ip连接。

数据帧传输支持text和binary两种方式:在使用text方式时,以0x00为起始点,以0xff结束,数据以utf-8编码置于中间;对于binary方式则没有结束标识,而是将数据帧长度置于数据前面。

2. 浏览器端 websocket编程接口

在浏览器端使用websocket之前,需要检测浏览器是否支持websocket,代码如下:

var socket=null; 
window.websocket = window.websocket || window.mozwebsocket; 
if (!window.websocket) { alert('error: websocket is not supported .'); } 
else{ socket = new websocket('ws://...');} 

websocket接口定义如下:

interface websocket : eventtarget { 
 readonly attribute domstring url; 
 // ready state 
 const unsigned short connecting = 0; 
 const unsigned short open = 1; 
 const unsigned short closing = 2; 
 const unsigned short closed = 3; 
 readonly attribute unsigned short readystate; 
 readonly attribute unsigned long bufferedamount; 
 // networking 
 attribute eventhandler onopen; 
 attribute eventhandler onerror; 
 attribute eventhandler onclose; 
 readonly attribute domstring extensions; 
 readonly attribute domstring protocol; 
 void close([clamp] optional unsigned short code, optional domstring reason); 
 // messaging 
 attribute eventhandler onmessage; 
 attribute domstring binarytype; 
 void send(domstring data); 
 void send(blob data); 
 void send(arraybuffer data); 
 void send(arraybufferview data); 
}; 

从上面定义中可以很清晰的看出:

  • 通过send()发向服务器送数据;
  • 通过close()关闭连接;
  • 通过注册事件函数 onopen,onerror,onmessage,onclose 来处理服响应.

在index.jsp中编写编写代码如下:

<!doctype html> 
<html> 
<head> 
<title>websocket demo</title> 
<style> 
body {padding: 40px;} 
#outputpanel {margin: 10px;padding:10px;background: #eee;border: 1px solid #000;min-height: 300px;} 
</style> 
</head> 
<body> 
<input type="text" id="messagebox" size="60" /> 
<input type="button" id="buttonsend" value="send message" /> 
<input type="button" id="buttonconnect" value="connect to server" /> 
<input type="button" id="buttonclose" value="disconnect" /> 
<br> 
<% out.println("session id = " + session.getid()); %> 
<div id="outputpanel"></div> 
</body> 
<script type="text/javascript"> 
 var infopanel = document.getelementbyid('outputpanel'); // 输出结果面板 
 var textbox = document.getelementbyid('messagebox'); // 消息输入框 
 var sendbutton = document.getelementbyid('buttonsend'); // 发送消息按钮 
 var connbutton = document.getelementbyid('buttonconnect');// 建立连接按钮 
 var discbutton = document.getelementbyid('buttonclose');// 断开连接按钮 
 // 控制台输出对象 
 var console = {log : function(text) {infopanel.innerhtml += text + "<br>";}}; 
 // websocket演示对象 
 var demo = { 
  socket : null, // websocket连接对象 
  host : '',  // websocket连接 url 
  connect : function() { // 连接服务器 
   window.websocket = window.websocket || window.mozwebsocket; 
   if (!window.websocket) { // 检测浏览器支持 
    console.log('error: websocket is not supported .'); 
    return; 
   } 
   this.socket = new websocket(this.host); // 创建连接并注册响应函数 
   this.socket.onopen = function(){console.log("websocket is opened .");}; 
   this.socket.onmessage = function(message) {console.log(message.data);}; 
   this.socket.onclose = function(){ 
    console.log("websocket is closed ."); 
    demo.socket = null; // 清理 
   }; 
  }, 
  send : function(message) { // 发送消息方法 
   if (this.socket) { 
    this.socket.send(message); 
    return true; 
   } 
   console.log('please connect to the server first !!!'); 
   return false; 
  } 
 }; 
 // 初始化websocket连接 url 
 demo.host=(window.location.protocol == 'http:') ? 'ws://' : 'wss://' ; 
 demo.host += window.location.host + '/hello/websocket/say'; 
 // 初始化按钮点击事件函数 
 sendbutton.onclick = function() { 
  var message = textbox.value; 
  if (!message) return; 
  if (!demo.send(message)) return; 
  textbox.value = ''; 
 }; 
 connbutton.onclick = function() { 
  if (!demo.socket) demo.connect(); 
  else console.log('websocket already exists .'); 
 }; 
 discbutton.onclick = function() { 
  if (demo.socket) demo.socket.close(); 
  else console.log('websocket is not found .'); 
 }; 
</script> 
</html> 

3. 服务器端websocket编程

tomcat 7提供了websocket支持,这里就以tomcat 7 为例,探索一下如何在服务器端进行websocket编程。需要加载的依赖包为 \lib\catalina.jar、\lib\tomcat-coyote.jar

这里有两个重要的类 :websocketservlet 和 streaminbound, 前者是一个容器,用来初始化websocket环境;后者是用来具体处理websocket请求和响应的。

编写一个servlet类,继承自websocket,实现其抽象方法即可,代码如下:

package websocket; 
 
import java.util.concurrent.atomic.atomicinteger; 
import javax.servlet.http.httpservletrequest; 
import org.apache.catalina.websocket.streaminbound; 
import org.apache.catalina.websocket.websocketservlet; 
 
public class hellowebsocketservlet extends websocketservlet { 
 private static final long serialversionuid = 1l; 
 
 private final atomicinteger connectionids = new atomicinteger(0); 
 @override 
 protected streaminbound createwebsocketinbound(string arg0, 
   httpservletrequest request) { 
  return new hellomessageinbound(connectionids.getandincrement(), request 
    .getsession().getid()); 
 } 
} 
package websocket; 
 
import java.io.ioexception; 
import java.io.inputstream; 
import java.io.reader; 
import java.nio.charbuffer; 
import org.apache.catalina.websocket.streaminbound; 
import org.apache.catalina.websocket.wsoutbound; 
 
public class hellomessageinbound extends streaminbound { 
 
 private string ws_name; 
 private final string format = "%s : %s"; 
 private final string prefix = "ws_"; 
 private string sessionid = ""; 
 
 public hellomessageinbound(int id, string _sessionid) { 
  this.ws_name = prefix + id; 
  this.sessionid = _sessionid; 
 } 
 
 @override 
 protected void ontextdata(reader reader) throws ioexception { 
  char[] charr = new char[1024]; 
  int len = reader.read(charr); 
  send(string.copyvalueof(charr, 0, len)); 
 } 
 
 @override 
 protected void onclose(int status) { 
  system.out.println(string.format(format, ws_name, "closing ......")); 
  super.onclose(status); 
 } 
 
 @override 
 protected void onopen(wsoutbound outbound) { 
  super.onopen(outbound); 
  try { 
   send("hello, my name is " + ws_name); 
   send("session id = " + this.sessionid); 
  } catch (ioexception e) { 
   e.printstacktrace(); 
  } 
 } 
 
 private void send(string message) throws ioexception { 
  message = string.format(format, ws_name, message); 
  system.out.println(message); 
  getwsoutbound().writetextmessage(charbuffer.wrap(message)); 
 } 
 
 @override 
 protected void onbinarydata(inputstream arg0) throws ioexception { 
 } 
} 

在web.xml中进行servlet配置:

<?xml version="1.0" encoding="utf-8"?> 
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" 
 xsi:schemalocation="http://java.sun.com/xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 
 <display-name>websocket demo</display-name> 
 <servlet> 
  <servlet-name>wshello</servlet-name> 
  <servlet-class>websocket.hellowebsocketservlet</servlet-class> 
 </servlet> 
 <servlet-mapping> 
  <servlet-name>wshello</servlet-name> 
  <url-pattern>/websocket/say</url-pattern> 
 </servlet-mapping> 
 
 <welcome-file-list> 
  <welcome-file>index.jsp</welcome-file> 
 </welcome-file-list> 
</web-app>

4. 结果


这里看到 websocket建立的连接所访问的session和http访问的session是一致的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网