4 changed files with 93 additions and 7 deletions
-
10src/main/java/com/iflytop/nuclear/NuclearApplication.java
-
19src/main/java/com/iflytop/nuclear/service/impl/TaskServiceImpl.java
-
68src/main/java/com/iflytop/nuclear/websocket/WebSocketClient.java
-
3src/main/resources/application-dev.yml
@ -0,0 +1,68 @@ |
|||
package com.iflytop.nuclear.websocket; |
|||
|
|||
import com.alibaba.fastjson.JSON; |
|||
import com.alibaba.fastjson.JSONObject; |
|||
import com.iflytop.nuclear.handler.MessageHandler; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.springframework.stereotype.Component; |
|||
import org.springframework.util.StringUtils; |
|||
|
|||
import javax.websocket.*; |
|||
import java.io.IOException; |
|||
import java.net.URI; |
|||
|
|||
/** |
|||
* @author cool |
|||
* @date 2023/7/4 19:12 |
|||
*/ |
|||
@ClientEndpoint |
|||
@Component |
|||
@Slf4j |
|||
public class WebSocketClient { |
|||
|
|||
@Autowired |
|||
MessageHandler messageHandler; |
|||
|
|||
private Session session; |
|||
|
|||
@OnOpen |
|||
public void onOpen(Session session) { |
|||
this.session = session; |
|||
} |
|||
|
|||
// WebSocketContainer container = ContainerProvider.getWebSocketContainer(); |
|||
// String uri ="ws://127.0.0.1:8888/websocket/123"; |
|||
// container.connectToServer(WebSocketClient.class, URI.create(uri)); |
|||
|
|||
@OnMessage |
|||
public void onMessage(String message) throws IOException { |
|||
if (!StringUtils.isEmpty(message)) { |
|||
try { |
|||
JSONObject jsonObject = JSON.parseObject(message); |
|||
String command = jsonObject.getString("command"); |
|||
// 根据command类型,分发给不同的handler和detection |
|||
if (!command.isEmpty()) { |
|||
messageHandler.dispatcher(command, jsonObject, this.session); |
|||
} |
|||
} catch (Exception e) { |
|||
JSONObject msg = new JSONObject(); |
|||
msg.put("message", "传输数据必须为包含command字段的JSON格式"); |
|||
this.session.getBasicRemote().sendText(msg.toString()); |
|||
e.printStackTrace(); |
|||
} |
|||
} |
|||
} |
|||
|
|||
@OnError |
|||
public void onError(Throwable t) { |
|||
t.printStackTrace(); |
|||
} |
|||
|
|||
public void sendMessage(String message) throws IOException { |
|||
if(this.session != null) { |
|||
this.session.getBasicRemote().sendText(message); |
|||
} |
|||
} |
|||
|
|||
} |
Write
Preview
Loading…
Cancel
Save
Reference in new issue