WebSocket的java和python使用
1、Java使用
参考博客: https://blog.csdn.net/moshowgame/article/details/80275084
1. 1 后端配置
1 import org.springframework.web.socket.server.standard.ServerEndpointExporter; 2 3 /** 4 * 在打包运行在外部服务器时,将该类中的@Configuration\ @Bean 注解去掉 5 * 本地运行时,需要上述注释 6 */ 7 //@Configuration 8 public class WebSocketConfig { 9 10 //@Bean 11 public ServerEndpointExporter serverEndpointExporter() { 12 return new ServerEndpointExporter(); 13 } 14 }
1 import java.io.IOException; 2 import java.util.Map; 3 import java.util.concurrent.CopyOnWriteArraySet; 4 5 import javax.annotation.PostConstruct; 6 import javax.websocket.OnClose; 7 import javax.websocket.OnError; 8 import javax.websocket.OnMessage; 9 import javax.websocket.OnOpen; 10 import javax.websocket.Session; 11 import javax.websocket.server.PathParam; 12 import javax.websocket.server.ServerEndpoint; 13 14 import cn.th.jump.demoboot.service.ClockBookingService; 15 import cn.th.jump.demoboot.service.OsInspectionServiceImpl; 16 import com.alibaba.fastjson.JSONObject; 17 import org.springframework.beans.factory.annotation.Autowired; 18 import org.springframework.stereotype.Component; 19 import cn.hutool.log.Log; 20 import cn.hutool.log.LogFactory; 21 22 23 @ServerEndpoint("/websocket") 24 @Component 25 public class WebSocketServer { 26 27 // https://blog.csdn.net/moshowgame/article/details/80275084 28 29 static Log log=LogFactory.get(WebSocketServer.class); 30 //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 31 private static int onlineCount = 0; 32 //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 33 private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>(); 34 35 //与某个客户端的连接会话,需要通过它来给客户端发送数据 36 private Session session; 37 38 public static WebSocketServer webSocketServer; 39 40 @PostConstruct 41 public void init() { 42 webSocketServer = this; 43 } 44 45 @Autowired 46 OsInspectionServiceImpl osInspectionService; 47 48 //接收sid 49 private String sid=""; 50 /** 51 * 连接建立成功调用的方法*/ 52 @OnOpen 53 public void onOpen(Session session,@PathParam("sid") String sid) { 54 this.session = session; 55 webSocketSet.add(this); //加入set中 56 addOnlineCount(); //在线数加1 57 //log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount()); 58 this.sid=sid; 59 try { 60 sendMessage("连接成功"); 61 } catch (IOException e) { 62 log.error("websocket IO异常"); 63 } 64 } 65 66 /** 67 * 连接关闭调用的方法 68 */ 69 @OnClose 70 public void onClose() { 71 webSocketSet.remove(this); //从set中删除 72 subOnlineCount(); //在线数减1 73 log.info("有一连接关闭!当前在线人数为" + getOnlineCount()); 74 } 75 76 /** 77 * 收到客户端消息后调用的方法 78 * 79 * @param message 客户端发送过来的消息*/ 80 @OnMessage 81 public void onMessage(String message, Session session) { 82 log.info("收到来自窗口"+sid+"的信息:"+message); 83 //群发消息 84 for (WebSocketServer item : webSocketSet) { 85 try { 86 87 /* 巡检设备ping通状态 已修改为直接跑脚本形式 88 JSONObject jsonObject = JSONObject.parseObject(message); 89 Map map = jsonObject; 90 log.info( jsonObject.toString() ); 91 log.info( map.get("unconnected").toString() ); 92 93 webSocketServer.osInspectionService.batchPing(map);*/ 94 95 item.sendMessage("fresh-"); 96 97 } catch (IOException e) { 98 e.printStackTrace(); 99 } 100 } 101 } 102 103 /** 104 * 105 * @param session 106 * @param error 107 */ 108 @OnError 109 public void onError(Session session, Throwable error) { 110 log.error("发生错误"); 111 error.printStackTrace(); 112 } 113 /** 114 * 实现服务器主动推送 115 */ 116 public void sendMessage(String message) throws IOException { 117 //this.session.getBasicRemote().sendText(message); 118 this.session.getBasicRemote().sendText(message); 119 } 120 121 122 /** 123 * 群发自定义消息 124 * */ 125 public static void sendInfo(String message) throws IOException { 126 log.info("推送消息到窗口 "+message,message); 127 for (WebSocketServer item : webSocketSet) { 128 try { 129 //这里可以设定只推送给这个sid的,为null则全部推送 130 item.sendMessage(message); 131 } catch (IOException e) { 132 continue; 133 } 134 } 135 } 136 137 public static synchronized int getOnlineCount() { 138 return onlineCount; 139 } 140 141 public static synchronized void addOnlineCount() { 142 WebSocketServer.onlineCount++; 143 } 144 145 public static synchronized void subOnlineCount() { 146 WebSocketServer.onlineCount--; 147 } 148 }
1.2 前端使用
1 <!-- 获取项目名称 --> 2 var projectname = "[[@{/}]]"; 3 projectname = projectname.split("/")[1]; 4 projectname = "/"+projectname; 5 6 <!-- websocket --> 7 var socket; 8 if(typeof(WebSocket) == "undefined") { 9 console.log("您的浏览器不支持WebSocket"); 10 }else{ 11 console.log("您的浏览器支持WebSocket"); 12 13 //实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接 14 15 socket = new WebSocket("ws://10.29.138.120:8080"+ projectname +"/websocket".replace("http","ws")); 16 17 //打开事件 18 socket.onopen = function() { 19 console.log("Socket 已打开"); 20 // socket.send("这是来自客户端的消息" + location.href + new Date()); 21 }; 22 23 //获得消息事件 24 socket.onmessage = function(msg) { 25 console.log(msg.data); 26 //发现消息进入,开始处理前端触发逻辑 27 refresh(); 28 }; 29 30 //关闭事件 31 socket.onclose = function() { 32 console.log("Socket已关闭"); 33 }; 34 35 //发生了错误事件 36 socket.onerror = function() { 37 toastr.error("Socket发生了错误"); 38 //此时可以尝试刷新页面 39 } 40 }
2、Python使用
1 import sys 2 import os 3 import re 4 import gc 5 import json 6 import logging 7 import telnetlib 8 import socket 9 from websocket import create_connection 10 11 global ws 12 13 try: 14 ws = create_connection("ws://10.130.35.93:8080/clockck/websocket") 15 # ws = create_connection("ws://10.22.115.88:8080/clockck/websocket") 16 result = ws.recv() 17 print "Received '%s'" % result 18 except socket.error as error: 19 print "==== websocket error" 20 21 def close_socket(): 22 try: 23 ws.close() # 需关闭连接 24 logger.debug("finish the test success") 25 except: 26 #ws = None 27 logger.debug(" try except finish the test ") 28 29 30 def switchCases(caseType, res): 31 try: 32 ws.send(json.dumps( sendBeginMsgFormat(sqlRes[caseType][0],caseType,g_logDir,dict["cardid"]))) # 通知服务器,执行用例开始 33 34 except: 35 ws.send(json.dumps(dict)) # 统一封装成json格式给服务器 36 tear_down()