此篇文章使用的是tomcat包下的類(lèi)來(lái)實(shí)現(xiàn)簡(jiǎn)單的Java websocket 服務(wù)端和客戶(hù)端。
1 引入包依賴(lài)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2 創(chuàng)建服務(wù)端
主要使用@ServerEndpoint勒葱、@OnOpen琅摩、@OnMessage序宦、@OnClose衰粹、@OnError這幾個(gè)注解溜畅,對(duì)應(yīng)的方法里可以帶下面的參數(shù)巫玻,當(dāng)然也可以為空,具體需要由開(kāi)發(fā)者定逗栽。
注解 | 釋義 | 參數(shù) |
---|---|---|
@ServerEndpoint | 注冊(cè)端點(diǎn) | |
@OnOpen | 連接時(shí)調(diào)用 | Session盖袭,EndpointConfig |
@OnMessage | 收到消息調(diào)用 | Session,String |
@OnClose | 連接關(guān)閉時(shí)調(diào)用 | Session彼宠,CloseReason |
@OnError | 發(fā)生錯(cuò)誤時(shí)調(diào)用 | Session鳄虱,Throwable |
2.1 端點(diǎn)發(fā)布
使用ServerEndpointExporter發(fā)布由@ServerEndpoint定義的端點(diǎn)。
@Configuration
public class JxConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
2.2 定義連接端點(diǎn)
使用@ServerEndpoint注解定義一個(gè)端點(diǎn)凭峡,且要用@Component注解交由spring 框架管理拙已,不然此端點(diǎn)無(wú)法發(fā)布使用。
@Component
@ServerEndpoint("/jx/{name}")
public class Server {
@OnOpen
public void onOpen(Session session, @PathParam("name") String name) {
System.out.println("名稱(chēng):" + name);
System.out.println(session.getId() + "客戶(hù)端連接");
}
@OnClose
public void onClose(Session session, CloseReason reason) {
System.out.println("client關(guān)閉");
System.out.println("關(guān)閉原因:" + reason.getCloseCode() + reason.getReasonPhrase());
}
@OnMessage
public void onMessage(Session session, String msg) {
System.out.println("client" + session.getId() + "接收到的消息:" + msg);
try {
//返回消息給客戶(hù)端
session.getBasicRemote().sendText("服務(wù)端收到消息:" + msg);
} catch (IOException e) {
e.printStackTrace();
}
}
@OnError
public void onError(Session session, Throwable throwable) {
System.out.println(session.getId() + "發(fā)生錯(cuò)誤");
throwable.printStackTrace();
}
}
3 創(chuàng)建客戶(hù)端
客戶(hù)端與服務(wù)端基本是一樣的摧冀,主要使用@ClientEndpoint來(lái)聲明一個(gè)客戶(hù)端倍踪,其他操作也是用@OnOpen、@OnMessage索昂、@OnClose建车、@OnError這幾個(gè)注解。
@ClientEndpoint
public class Client {
@OnOpen
public void onOpen(Session session) {
System.out.println(session.getId()+"客戶(hù)端連接");
}
@OnClose
public void onClose() {
System.out.println("client關(guān)閉");
}
@OnMessage
public void onMessage(String msg, Session session) {
System.out.println("client" + session.getId() + "接收到的消息:" + msg);
}
public static void main(String[] args) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
Session session = container.connectToServer(Client.class, URI.create("ws://localhost:8080/jx/tom"));
//控制臺(tái)輸入消息
Scanner scanner = new Scanner(System.in);
String msg;
//輸入quit退出
while (!"quit".equals(msg = scanner.nextLine())) {
session.getBasicRemote().sendText(msg);
}
session.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}