1、服务端
代码分为两部分:
一个是服务器终端类:用java注解来监听连接@ServerEndpoint、连接成功@OnOpen、连接失败@OnClose、收到消息等状态@OnMessage
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
@Component
@ServerEndpoint("/websocket/fqa")
public class QwenWebSocket {
@OnOpen
public void onOpen(Session session){
System.out.println("WebSocket opened: " + session.getId());
}
@OnMessage
public void onMessage(String message, Session session){
System.out.println("Message received: " + message);
try{
session.getBasicRemote().sendText("Echo: " + message);
}catch (IOException e){
e.printStackTrace();
}
}
@OnClose
public void onClose(Session session){
System.out.println("WebSocket closed: " + session.getId());
}
@OnError
public void onError(Throwable t){
t.printStackTrace();
}
}
一个是websocket的配置类,用于把spring中的ServerEndpointExporter对象注入进来
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
/**
* 这个bean的注册,用于扫描带有@ServerEndpoint的注解成为websocket,如果你使用外置的tomcat就不需要该配置文件
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
2、客户端
普通的java工程即可,不需要是spring。
import javax.websocket.*;
import java.net.URI;
@ClientEndpoint
public class MyWebSocketClient {
@OnOpen
public void onOpen(Session session){
System.out.println("Connected to server");
}
@OnMessage
public void onMessage(String message){
System.out.println("Received message: " + message);
}
@OnClose
public void onClose(CloseReason reason){
System.out.println("Closing: " + reason.getReasonPhrase());
}
public static void main(String[] args) {
try{
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
URI uri = URI.create("ws://localhost:8080/websocket/fqa");
Session session = container.connectToServer(MyWebSocketClient.class, uri);
session.getBasicRemote().sendText("I'm client!");
Thread.sleep(10000);
}catch(Exception e){
e.printStackTrace();
}
}
}
3、效果
客户端显示:
Connected to server
Received message: Echo: I'm client!
服务端显示:
WebSocket opened: 4
Message received: I'm client!
WebSocket closed: 4