1. 依赖
<span style="font-size:12px;"><dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-server</artifactId>
<version>1.13</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-client</artifactId>
<version>1.13</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-container-grizzly-server</artifactId>
<version>1.13</version>
</dependency></span>
2. server
package com.pechen.websocket_client;
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 gives the relative name for the end point This will be
* accessed via ws://localhost:8080/EchoChamber/echo Where
* "localhost" is the address of the host, "EchoChamber" is the
* name of the package and "echo" is the address to access this
* class from the server
*/
@ServerEndpoint("/myHandler")
public class WebsocketServerEndpoint {
/**
* @OnOpen allows us to intercept the creation of a new session. The session
* class allows us to send data to the user. In the method onOpen,
* we'll let the user know that the handshake was successful.
*/
@OnOpen
public void onOpen(Session session) {
try {
session.getBasicRemote().sendText("Connection Established");
}
catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* When a user sends a message to the server, this method will intercept the
* message and allow us to react to it. For now the message is read as a
* String.
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("from client: " + message);
try {
session.getBasicRemote().sendText("received: " + message);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* The user closes the connection.
*
* Note: you can't send messages to the client from this method
*/
@OnClose
public void onClose(Session session) {
try {
session.getBasicRemote().sendText("Connection destroyed.");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.pechen.websocket_client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.glassfish.tyrus.server.Server;
public class ServerAPP {
public static void main(String[] args) {
runServer();
}
public static void runServer() {
Server server = new Server("localhost", 8080, "", null,
WebsocketServerEndpoint.class);
try {
server.start();
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Press any key to stop the server.");
reader.readLine();
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
server.stop();
}
}
}
3. client
package com.pechen.websocket_client;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.CountDownLatch;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import org.apache.log4j.Logger;
import org.glassfish.tyrus.client.ClientManager;
import org.glassfish.tyrus.client.ClientProperties;
@ClientEndpoint
public class ClientEndPoing {
private static CountDownLatch latch;
private static Session session;
private Logger logger = Logger.getLogger(this.getClass().getName());
@OnOpen
public void onOpen(Session session) {
this.session = session;
System.out.println("websocket opening.");
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println(message);
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
this.session = null;
logger.info(String.format("Session closed because of %s", closeReason));
latch.countDown();
}
public static void sendMessage(String message) {
if (session == null)
return;
try {
session.getBasicRemote().sendText(message);
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
latch = new CountDownLatch(1);
ClientManager client = ClientManager.createClient();
try {
client.connectToServer(ClientEndPoing.class,
new URI("ws://localhost:8080/myHandler"));
for (int i = 0; i < 10; i++) {
sendMessage("message " + String.valueOf(i));
}
latch.await();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
4. client reconnection
public static void main(String[] args) {
latch = new CountDownLatch(1);
ClientManager client = ClientManager.createClient();
ClientManager.ReconnectHandler reconnectHandler = new ClientManager.ReconnectHandler() {
private int counter = 0;
@Override
public boolean onDisconnect(CloseReason closeReason) {
counter++;
if (counter <= 3) {
System.out.println("### Reconnecting... (reconnect count: " + counter + ")");
return true;
}
else {
return false;
}
}
@Override
public boolean onConnectFailure(Exception exception) {
counter++;
if (counter <= 3) {
System.out.println(
"### Reconnecting... (reconnect count: " + counter + ") " + exception.getMessage());
// Thread.sleep(...) or something other "sleep-like"
// expression can be put here - you might want
// to do it here to avoid potential DDoS when you don't
// limit number of reconnects.
return true;
}
else {
return false;
}
}
@Override
public long getDelay() {
return 1;
}
};
client.getProperties().put(ClientProperties.RECONNECT_HANDLER,
reconnectHandler);
try {
client.connectToServer(ClientEndPoing.class,
new URI("ws://localhost:8080/myHandler"));
for (int i = 0; i < 10; i++) {
sendMessage("message " + String.valueOf(i));
}
latch.await();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
Reference: https://tyrus.java.net/documentation/1.13/index/getting-started.html