流程: 后端开启线程监听某个端口是否接收到tcp的数据,如果接收到数据则向前端推送消息,前端接收到消息后进行接收消息的回调方法,将返回相应数据给后端,后端将生成数据,插入到数据库中
后端代码
@Configuration
public class WebsocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter()
{
return new ServerEndpointExporter();
}
}
websocket接口:
@Controller
@ServerEndpoint(value = "/mywebsocket/{id}")
public class WebsocketServlet {
private static CopyOnWriteArraySet<WebsocketServlet> webSocketSet = new CopyOnWriteArraySet<>();
private Session session = null;
private void sendMessage() throws IOException{
System.out.println("执行群发消息,sendMessage");
for(WebsocketServlet item:webSocketSet){
try{
item.session.getBasicRemote().sendText("1");
}catch (IOException e){
e.printStackTrace();;
continue;
}
}
}
@OnOpen
public void onOpen(Session session){
System.out.println("Session:"+session.getId()+"已经建立连接");
this.session=session;
webSocketSet.add(this);
try {
session.getBasicRemote().sendText("Connection Established");
} catch (IOException e) {
e.printStackTrace();
}
}
@OnMessage
public void onMessage(String message){
System.out.println("Message" + ":"+message);
}
@OnClose
public void onClose(Session session){
webSocketSet.remove(this);
System.out.println("session"+session.getId()+"has closed");
}
public void onError(Session session,Throwable t){
t.printStackTrace();
}
private boolean submit(String name) {
return true;
}
public void sendMessage(String message){
for (WebsocketServlet webSocket : webSocketSet){
System.out.println("广播消息:"+message);
try {
webSocket.session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
开启线程监听tcp连接:
@Component
public class TCPserver2 implements Callable {
@Autowired
WebsocketServlet websocketServlet;
@Override
public Object call() throws Exception {
ServerSocket server = new ServerSocket(8005);
while (true) {
Socket socket = server.accept();
new ServerReadThread(socket).start();
System.out.println(socket.getRemoteSocketAddress() + "上线了!");
}
}
class ServerReadThread extends Thread {
private Socket socket;
public ServerReadThread(Socket socket) {
this.socket = socket;
}
@SneakyThrows
@Override
public void run() {
try (
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());)
{
byte[] buffer = new byte[1024];
int sum = 0;
int len = in.read(buffer);
if (len != -1) {
String msg = buffer.toString();
System.out.println("8004接收到消息:" + msg);
websocketServlet.sendMessage("清洗结束!");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
System.out.println("closed");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
主启动类加上:
TCPserver2 tcPserver2 = SpringUtils.getBean(TCPserver2.class);
FutureTask<Integer> endSignal = new FutureTask<Integer>(tcPserver2);
new Thread(endSignal).start();
前端代码
data () {
return {
endsign:'no'
}
},
mounted(){
this. createWebsocket();
}
methods:{
createWebsocket() {
const httpURL = process.env.VUE_APP_DOMAIN;
this.websocket = new WebSocket(`ws://192.168.100.88:9001/mywebsocket/1`);
this.websocket.onerror = this.websocketOnerror;
this.websocket.onopen = this.websocketOnopen;
this.websocket.onmessage = this.websocketOnmessage;
this.websocket.onclose = this.websocketOnclose;
this.websocket.onbeforeunload = this.websocketOnbeforeunload;
},
websocketOnerror() {
console.log('连接发生错误的回调方法');
},
websocketOnopen() {
console.log('连接成功建立的回调方法');
},
websocketOnmessage(event) {
const data = event.data;
console.log('接收到消息的回调方法', data);
this.sendTime()
this.endsign='yes'
},
websocketOnclose() {
console.log('连接关闭的回调方法');
},
websocketOnbeforeunload() {
this.closeWebSocket();
console.log('监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常');
},
closeWebSocket() {
this.websocket.close();
}
}
}
测试: 用网络调试精灵发送给后端一个tcp连接,然后可以看到前端显示接收到推送的消息: 后端也处理了数据并添加到了数据库中:
|