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#客户端界面展示

  • 相关阅读:
    Oracle分页问题
    win10系统vs2008环境wince项目无法创建问题
    工作满十年了
    让Vs2013 完美支持EF6.1 Code First with Oracle 2015年12月24日更新
    Oracle DMP 操作笔记之根据DMP逆向推导出导出的表空间名称
    【转】如何在 Eclipse 中進行 TFS 的版本管控
    【转】什麼是 Team Explorer Everywhere 2010 ?TFS 專用的 Eclipse 整合套件的安裝與設定
    [转]有关USES_CONVERSION
    [转]使用VC/MFC创建一个线程池
    IT男的”幸福”生活
  • 原文地址:https://www.cnblogs.com/Im-Victor/p/11136555.html
Copyright © 2011-2022 走看看