zoukankan      html  css  js  c++  java
  • Socket通讯-C#客户端与Java服务端通讯(发送消息和文件)

    设计思路

    使用websocket通信,客户端采用C#开发界面,服务端使用Java开发,最终实现Java服务端向C#客户端发送消息和文件,C#客户端实现语音广播的功能。

    Java服务端设计

    package servlet.websocket;
    
    import java.io.IOException;
    import java.util.Map;
    import java.util.concurrent.ConcurrentHashMap;
    import javax.websocket.OnClose;
    import javax.websocket.OnError;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.Session;
    import javax.websocket.server.PathParam;
    import javax.websocket.server.ServerEndpoint;
    
    import servlet.Log;
    
    /**
     * websocket服务端
     * 
     * @author leibf
     *
     */
    @ServerEndpoint(value = "/websocket/{clientId}")
    public class WebSocketServer {
        private final Log log = new Log(WebSocketServer.class);
        private Session session;
        private String clientId;
        private static Map<String, WebSocketServer> clients = new ConcurrentHashMap<String, WebSocketServer>();
    
        // 连接时执行
        @OnOpen
        public void onOpen(@PathParam("clientId") String clientId, Session session) throws IOException {
            this.session = session;
            this.clientId = clientId;
            clients.put(clientId, this);
            log.info("新连接:" + clientId);
        }
    
        // 关闭时执行
        @OnClose
        public void onClose(@PathParam("clientId") String clientId, Session session) {
            clients.remove(clientId);
    
            log.info("连接 " + clientId + " 关闭");
        }
    
        // 收到消息时执行
        @OnMessage
        public void onMessage(String message, Session session) throws IOException {
            log.info("收到用户的消息: "+  message);
            /*if("getMpDefsAndRtDatas".equals(message)){
                String msg = UnityServlet.getInstance().getAllMpDefsAndRtDatas();
                this.sendMessage(session, msg);
            }*/
        }
    
        // 连接错误时执行
        @OnError
        public void onError(@PathParam("clientId") String clientId, Throwable error, Session session) {
            log.info("用户id为:" + clientId + "的连接发送错误");
            error.printStackTrace();
        }
    
        /**
         * 发送消息给某个客户端
         * @param message
         * @param To
         * @throws IOException
         */
        public static void sendMessageTo(String message, String To) throws IOException {
            for (WebSocketServer item : clients.values()) {
                if (item.clientId.equals(To))
                    item.session.getAsyncRemote().sendText(message);
            }
        }
        
        /**
         * 发送消息给某些客户端
         * @param message
         * @param To
         * @throws IOException
         */
        public static void sendMessageToSomeone(String message, String To) throws IOException {
            for (WebSocketServer item : clients.values()) {
                if (item.clientId.startsWith(To))
                    item.session.getAsyncRemote().sendText(message);
            }
        }
    
        /**
         * 发送消息给所有客户端
         * @param message
         * @throws IOException
         */
        public static void sendMessageAll(String message) throws IOException {
            for (WebSocketServer item : clients.values()) {
                item.session.getAsyncRemote().sendText(message);
            }
        }
        
        /**
         * 发送消息
         * @param session
         * @param message
         * @throws IOException
         */
        private void sendMessage(Session session,String message) throws IOException{
            session.getBasicRemote().sendText(message);
        }
    }
    Java端发送请求指令
    
    String clientId = "broadcast";
    try {
        WebSocketServer.sendMessageTo("broadcast",clientId);
    } catch (IOException e) {
        e.printStackTrace();
    }

    C#客户端设计

    websocket连接

    WebSocket websocket = null;
    private void websocket_MessageReceived(object sender, MessageReceivedEventArgs e){
        //接收服务端发来的消息
        MessageReceivedEventArgs responseMsg = (MessageReceivedEventArgs)e; 
        string strMsg = responseMsg.Message;
        if(strMsg.Equals("broadcast")){
            websocketToPlay();
        }else if(strMsg.Equals("broadcastStop")){
            websocketToStop(sender,e);
        }
    }
            
    private void websocket_Closed(object sender, EventArgs e){
         DisplayStatusInfo("websocket connect failed!");
    }
    
    private void websocket_Opened(object sender, EventArgs e){
         DisplayStatusInfo("websocket connect success!");
    }
    
    //websocket连接
    private void connectWebsocket(){
        websocket = new WebSocket("ws://localhost:8080/FrameServlet/websocket/broadcast");
        websocket.Opened += websocket_Opened;
        websocket.Closed += websocket_Closed;
        websocket.MessageReceived += websocket_MessageReceived;
        websocket.Open();
    }

    跨线程操作控件 --- InvokeRequired属性与Invoke方法

    private delegate void DoLog(string msg);
    private void DisplayStatusInfo(string msg)
    {
        if (this.InvokeRequired)
        {
            DoLog doLog = new DoLog(DisplayStatusInfo);
            this.Invoke(doLog, new object[] { msg });
         }else{
            if (msg.Trim().Length > 0)
            {
                 ListBoxStatus.Items.Insert(0, msg);
                 if (ListBoxStatus.Items.Count > 100)
                 {
                     ListBoxStatus.Items.RemoveAt(ListBoxStatus.Items.Count - 1);
                 }
            }
         }
    }

    C#客户端界面展示

  • 相关阅读:
    SQL基础复习03--数据查询SQL语句(单表查询)
    SQL基础复习02--数据操纵SQL语句
    数据结构与算法01--复杂度
    SQL基础复习01--SQL基础与数据定义SQL语句
    Azure Data Studio的初步了解与使用
    ASP.NET Core Web API 使用DynamicLinq实现排序功能
    Vue3-说说Vue 3.0中Treeshaking特性?举例说明一下?
    JavaScript高频手写面试题
    Java常用文件操作-1
    Java 架构师之路(2)
  • 原文地址:https://www.cnblogs.com/Im-Victor/p/11136555.html
Copyright © 2011-2022 走看看