К серверу не подключаются клиенты? - C#
Формулировка задачи:
но в форме клиента написано, "Успешно подключен"
Сервер
namespace ChatServer { public partial class Form1 : Form { private delegate void UpdateStatusCallback(string strMessage); public Form1() { InitializeComponent(); } public class StatusChangedEventArgs : EventArgs { private string EventMsg; public string EventMessage { get { return EventMsg; } set { EventMsg = value; } } public StatusChangedEventArgs(string strEventMsg) { EventMsg = strEventMsg; } } public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e); class ChatServer { public static Hashtable htUsers = new Hashtable(50); public static Hashtable htConnections = new Hashtable(50); private IPAddress ipAddress; private TcpClient tcpClient; public static event StatusChangedEventHandler StatusChanged; private static StatusChangedEventArgs e; public ChatServer(IPAddress address) { ipAddress = address; } private Thread thrListener; private TcpListener tlsClient; bool ServRunning = false; public static void AddUser(TcpClient tcpUser, string strUsername) { ChatServer.htUsers.Add(strUsername, tcpUser); ChatServer.htConnections.Add(tcpUser, strUsername); SendAdminMessage(htConnections[tcpUser] + " подсоеднился"); } public static void RemoveUser(TcpClient tcpUser) { if (htConnections[tcpUser] != null) { SendAdminMessage(htConnections[tcpUser] + "отсоединился"); ChatServer.htUsers.Remove(ChatServer.htConnections[tcpUser]); ChatServer.htConnections.Remove(tcpUser); } } public static void OnStatusChanged(StatusChangedEventArgs e) { StatusChangedEventHandler statusHandler = StatusChanged; if (statusHandler != null) { statusHandler(null, e); } } public static void SendAdminMessage(string Message) { StreamWriter swSenderSender; e = new StatusChangedEventArgs("Пользователь" + Message); OnStatusChanged(e); TcpClient[] tcpClients = new TcpClient[ChatServer.htUsers.Count]; ChatServer.htUsers.Values.CopyTo(tcpClients, 0); for (int i = 0; i < tcpClients.Length; i++) { try { if (Message.Trim() == "" || tcpClients[i] == null) { continue; } swSenderSender = new StreamWriter(tcpClients[i].GetStream()); swSenderSender.WriteLine("Пользователь" + Message); swSenderSender.Flush(); swSenderSender = null; } catch { RemoveUser(tcpClients[i]); } } } public void StartListening() { IPAddress ipaLocal = ipAddress; tlsClient = new TcpListener(1986); tlsClient.Start(); ServRunning = true; thrListener = new Thread(KeepListening); thrListener.Start(); } private void KeepListening() { while (ServRunning == true) { tcpClient = tlsClient.AcceptTcpClient(); Connection newConnection = new Connection(tcpClient); } } } class Connection { TcpClient tcpClient; private Thread thrSender; private StreamReader srReceiver; private StreamWriter swSender; private string currUser; private string strResponse; public Connection(TcpClient tcpCon) { tcpClient = tcpCon; thrSender = new Thread(AcceptClient); thrSender.Start(); } private void CloseConnection() { tcpClient.Close(); srReceiver.Close(); swSender.Close(); } private void AcceptClient() { srReceiver = new System.IO.StreamReader(tcpClient.GetStream()); swSender = new System.IO.StreamWriter(tcpClient.GetStream()); currUser = srReceiver.ReadLine(); if (currUser != "") { if (ChatServer.htUsers.Contains(currUser) == true) { swSender.WriteLine("Это имя пользователя уже задействовано"); swSender.Flush(); CloseConnection(); return; } else if (currUser == "Пользователь") { swSender.WriteLine("This username is reserved"); swSender.Flush(); CloseConnection(); return; } else { swSender.WriteLine("1"); swSender.Flush(); } } else { CloseConnection(); return; } } } private void btnListen_Click(object sender, EventArgs e) { IPAddress ipAddr = IPAddress.Parse(txtIP.Text); ChatServer mainServer = new ChatServer(ipAddr); ChatServer.StatusChanged += new StatusChangedEventHandler(mainServer_StatusChanged); mainServer.StartListening(); txtLog.AppendText("Monitoring for connections...\r\n"); } public void mainServer_StatusChanged(object sender, StatusChangedEventArgs e) { this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { e.EventMessage }); } private void UpdateStatus(string strMessage) { txtLog.AppendText(strMessage + "\r\n"); } } }
Решение задачи: «К серверу не подключаются клиенты?»
textual
Листинг программы
namespace ChatClient { public partial class Form1 : Form { private string UserName = "Unknown"; private StreamWriter swSender; private StreamReader srReceiver; private TcpClient tcpServer; private delegate void UpdateLogCallback(string strMessage); private delegate void CloseConnectionCallback(string strReason); private Thread thrMessaging; private IPAddress ipAddr; private bool Connected; public Form1() { Application.ApplicationExit +=new EventHandler(OnApplicationExit); InitializeComponent(); } public void OnApplicationExit(object sender, EventArgs e) { if (Connected == true) { Connected = false; swSender.Close(); srReceiver.Close(); tcpServer.Close(); } } private void btnConnect_Click(object sender, EventArgs e) { if (Connected == false) { InitializeConnection(); } else { CloseConnection("Отключен по требованию пользователя"); } } private void InitializeConnection() { ipAddr = IPAddress.Parse(txtIp.Text); tcpServer = new TcpClient(); tcpServer.Connect(ipAddr, 1986); Connected = true; UserName = txtUser.Text; txtIp.Enabled = false; txtUser.Enabled = false; btnConnect.Text = "Отключить"; swSender = new StreamWriter(tcpServer.GetStream()); swSender.WriteLine(txtUser.Text); swSender.Flush(); thrMessaging = new Thread(new ThreadStart(ReceiveMessages)); thrMessaging.Start(); } private void ReceiveMessages() { srReceiver = new StreamReader(tcpServer.GetStream()); string ConResponse = srReceiver.ReadLine(); if (ConResponse[0] == '1') { this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { "Подключение успешно" }); } else { string Reason = "Не подключен: "; Reason += ConResponse.Substring(2, ConResponse.Length - 2); this.Invoke(new CloseConnectionCallback(this.CloseConnection), new object[] { Reason }); return; } while (Connected) { this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { srReceiver.ReadLine() }); } } private void UpdateLog(string strMessage) { txtLog.AppendText(strMessage + "\r\n"); } private void CloseConnection(string Reason) { txtLog.AppendText(Reason + "\r\n"); txtIp.Enabled = true; txtUser.Enabled = true; btnConnect.Text = "Connect"; Connected = false; swSender.Close(); srReceiver.Close(); tcpServer.Close(); } } }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д