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);
}
}
}
}
往期精彩内容:
[Java知识体系总结(2021版)](
)
[Java多线程基础知识总结(绝对经典)](
)
[超详细的springBoot学习笔记](
)
[常见数据结构与算法整理总结](
)
# 更多:Java进阶核心知识集
包含:JVM,JAVA集合,网络,JAVA多线程并发,JAVA基础,Spring原理,微服务,Zookeeper,Kafka,RabbitMQ,Hbase,MongoDB,Cassandra,设计模式,负载均衡,数据库,一致性哈希,JAVA算法,数据结构,加密算法,分布式缓存等等
![image](https://img-blog.csdnimg.cn/img_convert/00700af7bf8db979850ddbc156bbc939.png)
> **[CodeChina开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频】](https://codechina.csdn.net/m0_60958482/java-p7)**
# 高效学习视频
okeeper,Kafka,RabbitMQ,Hbase,MongoDB,Cassandra,设计模式,负载均衡,数据库,一致性哈希,JAVA算法,数据结构,加密算法,分布式缓存等等
[外链图片转存中...(img-cs2P8inB-1630407344674)]
> **[CodeChina开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频】](https://codechina.csdn.net/m0_60958482/java-p7)**
# 高效学习视频