1. Introduction
The HTML5 specification brought the capability for web browsers to establish full-duplex TCP connections with websocket compliant servers.
In other words, browsers are now able to establish a connection with a server and keep sending or receiving data through that same established communication channel without the need of the overhead introduced by the HTTP protocol itself.
In this tutorial we will implement a simple websocket server endpoint in a Java EE environment and also the respective client-side infrastructure for sending and receiving data.
This tutorial considers the following environment:
- Ubuntu 12.04
- JDK 1.7.0.21
- Glassfish 4.0
2. WebSocket server endpoint
Let's define a Java EE websocket server endpoint:
package com.byteslounge.websockets;import java.io.IOException;import javax.websocket.OnClose;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;@ServerEndpoint("/websocket")publicclassWebSocketTest{@OnMessagepublicvoid onMessage(String message,Session session)throwsIOException,InterruptedException{// Print the client message for testing purposesSystem.out.println("Received: "+ message);// Send the first message to the client session.getBasicRemote().sendText("This is the first server message");// Send 3 messages to the client every 5 secondsint sentMessages =0;while(sentMessages <3){Thread.sleep(5000); session.getBasicRemote(). sendText("This is an intermediate server message. Count: "+ sentMessages); sentMessages++;}// Send a final message to the client session.getBasicRemote().sendText("This is the last server message");}@OnOpenpublicvoid onOpen(){System.out.println("Client connected");}@OnClosepublicvoid onClose(){System.out.println("Connection closed");}}
As you may have already noticed we are importing several classes from javax.websocketpackage.
@ServerEndpoint annotation is used at type level and defines the current class as a websocket server endpoint. The value used in this annotation represents the URL where the endpoint will be listening for client connections.
onOpen and onClose methods are annotated with @OnOpen and @OnClose respectively. These annotations are almost self-explanatory: They define which methods will be called upon a new client connection and disconnection.
Method onMessage is annotated with @OnMessage. This annotation defines which method will be called when a new message is received from the client. Note that this method may be defined with an optional parameter of type javax.websocket.Session (in our case thesession parameter). If this parameter is defined the container will inject the session that is associated with the current client that sent the message being handled.
In our case we are just writing the client message content to the standard output. Then we proceed to send a message to the client followed by 3 test messages with a 5 second interval. Finally we send a final message to the client.
3. Client side
Now we need to write the client-side of our websocket test application:
<!DOCTYPE html><html><head><title>Testing websockets</title></head><body><div><inputtype="submit"value="Start"onclick="start()"/></div><divid="messages"></div><scripttype="text/javascript">var webSocket =newWebSocket('ws://localhost:8080/byteslounge/websocket'); webSocket.onerror =function(event){ onError(event)}; webSocket.onopen =function(event){ onOpen(event)}; webSocket.onmessage =function(event){ onMessage(event)};function onMessage(event){ document.getElementById('messages').innerHTML +='<br />'+ event.data;}function onOpen(event){ document.getElementById('messages').innerHTML ='Connection established';}function onError(event){ alert(event.data);}function start(){ webSocket.send('hello');returnfalse;}</script></body></html>
This is a simple test page that contains the JavaScript that will create a websocket connection to out websocket server endpoint.
onOpen method will be called when we establish a connection with the server endpoint.
onError method is called when an error occurs during client-server communication.
onMessage method will be called when a message is received from the server. In our case we are just appending the messages received from the server to the DOM.
We connect to the websocket server endpoint by using the construct new WebSocket() and passing the endpoint URL:
ws://localhost:8080/byteslounge/websocket
4. Testing
We may now test our application by accessing the testing page:
http://localhost:8080/byteslounge/page.html
We will see the Connection established message as expected:
Now as soon as we press the button we will send the initial message to the server through the websocket and receive the subsequent test messages sent by the server:
5. WebSockets Handshake
The TCP connection between the client and the server is established after the occurrence of a handshake over the HTTP protocol. It's easy to observe the handshake by using some HTTP traffic debugger. As soon as we create the WebSocket instance in the client the following request and respective server response will occur:
Note: we will only include HTTP headers that are relevant to the websockets handshake
Request:
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Key: wVlUJ/tu9g6EBZEh51iDvQ==
Response:
Upgrade: websocket
Sec-WebSocket-Accept: 2TNh+0h5gTX019lci6mnvS66PSY=
Note that the client is requesting the protocol to be upgraded to the WebSocket protocol by using Connection: Upgrade and Upgrade: websocket HTTP headers. The server response states that the client request was accepted and it will change protocol to WebSocket (using HTTP status code 101):
HTTP/1.1 101 Web Socket Protocol Handshake
6. Downloadable sample
The example source code is available for download at the end of this page. The test was executed in Glassfish 4 (you will need a Java EE 7 compliant application server).
相关推荐
java 异步http和websocket客户端 java 异步http和websocket客户端 java 异步http和websocket客户端 java 异步http和websocket客户端 java 异步http和websocket客户端 java 异步http和websocket客户端 java 异步http...
java html js websocket
HTML5 websocket 聊天 java tomcat8
使用javaEE7的websocket技术,tomcat7容器 + html5 完成即时通信样例
import org.java_websocket.WebSocket; import org.java_websocket.WebSocketImpl; import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ClientHandshake; import org.java_...
《HTML5 WebSocket权威指南》是HTML5 WebSocket领域最权威的著作之一,它系统、全面地讲解了HTML5 WebSocket的各个方面,是Web开发人员和架构师学习WebSocket的最佳选择。书中讨论了基于WebSocket的架构师如何减少...
资源名称:HTML5 WebSocket权威指南内容简介:《HTML5 WebSocket权威指南》是HTML5 WebSocket领域最权威的著作之一,它系统、全面地讲解了HTML5 WebSocket的各个方面,是Web开发人员和架构师学习WebSocket的最佳选择...
- java 后端源码包 - websocket client 四种创建方式 1. 第一种方式 WebSocketClient 注入方式 2. 第二种方式 @ClientEndpoint 注解方式 3. 第三种方式 extends WebSocketClient 的方式 4. 第四种方式 @...
java写的websocket客户端,包含心跳监测。 此架包可解决问题:系统使用websocket 访问远程上的实时数据,但是有时候会停止更新实时数据,只要重启了自己的系统,就会继续更新数据了,此包可以完美解决此问题。
java 基于websocket实现的视频聊天,解压项目到对应位置部署到tomcat8即可使用
基于HTML5+WebSocket+JAVA的棋牌游戏五子棋程序,IDEA完整工程包src\main\java\com\chanming\common,main\java\com\chanming\websockets
支持Java Android websocket即时通讯 简单快速
基于html5websocket java实现简单通讯 index.jsp在输入框输入1234id5发送就可以发送给index1.jsp index1.jsp在输入框输入12332234id4发送就可以发送给index.jsp id前的消息随意,后面跟着要发送目标的id即可
java-ee-html5-websocket-example java-ee-html5-websocket-example
java实现websocket客户端与服务端的连接
java_websocket.jar最新jar包 可用java实现websocket客户端,使用demo: https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/example/ExampleClient.java
java tomcat 7.0.42 websocket可使用java tomcat 7.0.42 websocket可使用java tomcat 7.0.42 websocket可使用java tomcat 7.0.42 websocket可使用
websocket长连接,实现实时同步,可借鉴
主要介绍了java 实现websocket的两种方式实例详解,一种使用tomcat的websocket实现,一种使用spring的websocket,本文通过代码给大家介绍的非常详细,需要的朋友可以参考下