void Listening() { while (true) { User user = new User(); user.socket = server.Accept(); try { user.username = MyNetwork.Read(user.socket); } catch { ShowMsg("A new connection lost when sending username. " + "(" + user.socket.RemoteEndPoint.ToString() + ")"); continue; } if (bannedIp.Contains(user.IP)) //Banned IP { SendToUser(user, "/refuse_banned"); ShowMsg("A new connection was refused because its IP has been banned. " + "(" + user.username + ", " + user.socket.RemoteEndPoint.ToString() + ")"); continue; } if (users.ContainsKey(user.username)) //Duplicate Name { SendToUser(user, "/refuse_duplicate"); ShowMsg("A new connection was refused because of its duplicated username. " + "(" + user.username + ", " + user.socket.RemoteEndPoint.ToString() + ")"); continue; } users.Add(user.username, user); ShowMsg("A new connection builded. " + "(" + user.username + ", " + user.socket.RemoteEndPoint.ToString() + ")"); Broadcast(user.username + " entered the chatroom."); Thread read = new Thread(delegate() { ReadAndBroadcast(user); }); read.IsBackground = true; read.Start(); } }
void ReadAndBroadcast(User user) { try { while (true) { string text = MyNetwork.Read(user.socket); Broadcast(user.username + ": " + text); } } catch { Offline(user); } }
public override void Send(string text) { Thread tSendToServer = new Thread(delegate() { try { MyNetwork.Write(client, text); } catch { ConnectionLost(); } }); tSendToServer.IsBackground = true; tSendToServer.Start(); // Echo text will be sent back by the server }
public void SendToUser(User user, string text, CallBack callBack = null) { Thread tSendToUser = new Thread(delegate() { try { MyNetwork.Write(user.socket, text); } catch { Offline(user); } if (callBack != null) { callBack(); } }); tSendToUser.IsBackground = true; tSendToUser.Start(); }
void Connect(string ip, int port) { try { client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(ip, port); MyNetwork.Write(client, username); //Send username } catch { ConnectionLost(); return; } EnableInput(); Thread tRAA = new Thread(delegate() { ReadAndAct(); }); tRAA.IsBackground = true; tRAA.Start(); }
void ReadAndAct() { while (true) { string text; try { text = MyNetwork.Read(client); } catch { ConnectionLost(); return; } if (text[0] == '/') { OptCmdFromServer(text); } else { ShowMsg(text); } } }