Java服務端與C#客戶端實現websocket通訊(發送消息和文件)

設計思路java

使用websocket通訊,客戶端採用C#開發界面,服務端使用Java開發,最終實現Java服務端向C#客戶端發送消息和文件,C#客戶端實現語音廣播的功能。web

Java服務端設計websocket

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端發送請求指令session

String clientId = "broadcast";
try {
	WebSocketServer.sendMessageTo("broadcast",clientId);
} catch (IOException e) {
	e.printStackTrace();
}

C#客戶端設計socket

websocket鏈接ui

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方法this

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#客戶端界面展現.net

 

江疏影講Java@目錄線程

相關文章
相關標籤/搜索