2023年7月15日发(作者:)
socket双向通信c语⾔,WebSocket实现实时双向通信1.什么是websocketWebSocket协议是基于TCP的⼀种新的⽹络协议。它实现了浏览器与服务器全双⼯(full-duplex)通信——允许服务器主动发送信息给客户端。2. http、websocket 、socket 区别案很简单,因为 HTTP 协议有⼀个缺陷:通信只能由客户端发起,HTTP 协议做不到服务器主动向客户端推送信息。WebSocket与Socket的关系Socket其实并不是⼀个协议,⽽是为了⽅便使⽤TCP或UDP⽽抽象出来的⼀层,是位于应⽤层和传输控制层之间的⼀组接⼝。当两台主机通信时,必须通过Socket连接,Socket则利⽤TCP/IP协议建⽴TCP连接。TCP连接则更依靠于底层的IP协议,IP协议的连接则依赖于链路层等更低层次。WebSocket则是⼀个典型的应⽤层协议。Socket是传输控制层协议,WebSocket是应⽤层协议。3.服务端消息推送``/*** 开启 websocket ⽀持* 配置WebSocketEndpointServer* 如果使⽤独⽴的servlet容器,不是使⽤SpringBoot的内置容器* 不需要注⼊ServerEndpointExporter, 它将由容器⾃⼰提供和管理*/@Configurationpublic class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}}@ServerEndpoint("/xxxx/{userId}")@Componentpublic class WebSocketServer {static Log log=();/**静态变量,⽤来记录当前在线连接数。应该把它设计成线程安全的。*/private static AtomicInteger onlineCount = new AtomicInteger(0);/**concurrent包的线程安全Set,⽤来存放每个客户端对应的MyWebSocket对象。*/private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>();/**与某个客户端的连接会话,需要通过它来给客户端发送数据*/private Session session;/**接收userId*/private String userId="";/*** 连接建⽴成功调⽤的⽅法*/@OnOpenpublic void onOpen(Session session,@PathParam("userId") String userId) {n = session;=userId;if(nsKey(userId)){(userId);(userId,this);//加⼊set中}else{(userId,this);//加⼊set中addOnlineCount();//在线数加1}("⽤户连接:"+userId+",当前在线⼈数为:" + getOnlineCount());try {sendMessage("连接成功");} catch (IOException e) {("⽤户:"+userId+",⽹络异常");}}/*** 连接关闭调⽤的⽅法*/@OnClosepublic void onClose() {if(nsKey(userId)){(userId);//从set中删除subOnlineCount();}("⽤户退出:"+userId+",当前在线⼈数为:" + getOnlineCount());}/*** 收到客户端消息后调⽤的⽅法** @param message 客户端发送过来的消息*/@OnMessagepublic void onMessage(String message, Session session) {("收到客户端消息:"+userId+",报⽂:"+message);//可以群发消息//消息保存到数据库、redisif(!y(message)){try {("接收到消息 "+ message);}catch (Exception e){tackTrace();}}}/**** @param session* @param error*/@OnErrorpublic void onError(Session session, Throwable error) {("⽤户错误:"++",原因:"+sage());tackTrace();}/*** 实现服务器主动推送*/public void sendMessage(String message) throws IOException {icRemote().sendText(message);}/*** 实现服务器主动推送*/public void sendMessageAsync(String message) {ncRemote().sendText(message);}/*** 发送⾃定义消息* */public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {("发送消息到:"+userId+",报⽂:"+message);if(!y(userId)&&nsKey(userId)){(userId).sendMessage(message);}else{("⽤户"+userId+",不在线!");}}/*** 发送⾃定义消息* */public static void sendInfo(String message) throws IOException {("群发送消息:"+message);if(y()){("⽆⽤户在线!");return;}for(Entry entry:et()){ue().sendMessage(message);}}public static synchronized int getOnlineCount() {return ();}public static synchronized void addOnlineCount() {Get(1);}public static synchronized void subOnlineCount() {Get(-1);}}4 . 客户端-html 通信var socket;if(typeof(WebSocket) == "undefined") {("您的浏览器不⽀持WebSocket");}else{("您的浏览器⽀持WebSocket");var socketUrl="localhost:9999/xxx/xxx/"+$("#userId").val();socketUrl=e("https","ws").replace("http","ws");(socketUrl);if(socket!=null){();socket=null;}socket = new WebSocket(socketUrl);//打开事件 = function() {("websocket已打开");//("这是来⾃客户端的消息" + + new Date());};//获得消息事件age = function(msg) {();alert("收到服务端推送消息:"+);//发现消息进⼊ 开始处理前端触发逻辑};//关闭事件e = function() {("websocket已关闭");};//发⽣了错误事件r = function() {("websocket发⽣了错误");}}5.客户端-Android实现
发布者:admin,转转请注明出处:http://www.yc00.com/web/1689409629a243453.html
评论列表(0条)