/// <summary> /// 以送信息给所有客户端 /// </summary> /// <param name="msg"></param> public void SendMsgToAllClient(string msg) { lockSlim.EnterReadLock(); try { foreach (var item in dictsocket) { if (SocketTools.IsSocketConnected(item.Value.socket)) { item.Value.socket.Send(SocketTools.GetBytes(msg, IsOpenDesEnc)); } else { item.Value.socket.Close(); OnDebug?.Invoke($"The client with ip {item.Key} has logged out and can't send a message."); } } } catch (Exception ex) { OnError?.Invoke($"Error when sending to all clients:{ex.ToString()}"); } finally { lockSlim.ExitReadLock(); } }
/// <summary> /// 开始服务器 /// </summary> /// <param name="port">端口号</param> /// <param name="count">连接队列总数(默认50)</param> /// <param name="ip">ip地址(默认本机ip)</param> public void StartServer(int port, int count = 50, string ip = "127.0.0.1") { socketWatch = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ipAdr = IPAddress.Parse(ip); IPEndPoint iPEnd = new IPEndPoint(ipAdr, port); try { socketWatch.Bind(iPEnd); } catch (Exception ex) { OnError?.Invoke($"Startup exception : {ex.ToString()}"); OnSuccess?.Invoke(false); return; } socketWatch.Listen(count); //开启心脏检测 Task.Run(() => { while (true) { HearBeat(); Thread.Sleep(HeartbeatCheckInterval); } }); // 监听客户端请求的方法,线程 Task.Run(() => { while (true) { System.Net.Sockets.Socket conn = socketWatch.Accept(); string socketip = conn.RemoteEndPoint.ToString(); conn.Send(SocketTools.GetBytes("YouIP," + socketip, IsOpenDesEnc)); Thread thr = new Thread(RecMsg); thr.IsBackground = true; thr.Start(conn); string id; AddSocketClient(socketip, conn, thr, out id); OnClientAdd?.Invoke(this, new SocketArgs(new ClientInfo() { ip = socketip, id = id })); } }); OnSuccess?.Invoke(true); }
/// <summary> /// 发送消息 /// </summary> /// <param name="msg"></param> public void SendMsg(string msg) { if (mySocket.Connected) { mySocket.Send(SocketTools.GetBytes(msg, IsOpenDesEnc)); } else { OnMessage?.Invoke("Not connected to the server~"); } }
/// <summary> /// 通过ip发送信息给客户端 /// </summary> /// <param name="ip"></param> /// <param name="msg"></param> public bool SendMsgToClientForIP(string ip, string msg) { lockSlim.EnterReadLock(); bool isok = true; try { if (dictsocket.ContainsKey(ip.Trim())) { ClientMode clientMode = dictsocket[ip.Trim()]; if (SocketTools.IsSocketConnected(clientMode.socket)) { clientMode.socket.Send(SocketTools.GetBytes(msg, IsOpenDesEnc)); isok = true; } else { clientMode.socket.Close(); OnDebug?.Invoke($"The client with ip {clientMode.ip} has logged out and can't send a message."); isok = false; } } } catch (Exception ex) { OnError?.Invoke($"Error when sending to the client:{ex.ToString()}"); isok = false; } finally { lockSlim.ExitReadLock(); } return(isok); }