private void newUserClientThreadMethod(Object ouserclient) { UserClient userclient = (UserClient)ouserclient; while (true) { try { string userReaderStr = userclient.binaryreader.ReadString(); string[] splitedStrs = userReaderStr.Split(','); switch (splitedStrs[0]) { case "message": chatRecordList.Items.Add("[" + splitedStrs[1] + "]对[" + splitedStrs[2] + "]说:" + splitedStrs[3]); foreach (UserClient user in userLists) { if (splitedStrs[2] == user.userName) { user.binarywriter.Write(userReaderStr); user.binarywriter.Flush(); } } break; case "connect": userclient.userName = splitedStrs[1]; userLists.Add(userclient); userList.Items.Add(splitedStrs[1]); chatRecordList.Items.Add("[Tips]:" + splitedStrs[1] + " 已加入聊天"); sendUserLists(); break; case "bye": string tempStr = ""; foreach (UserClient user in userLists) { if (user.userName == splitedStrs[1]) { tempStr = "[Tips]: " + user.userName + "已退出聊天"; chatRecordList.Items.Add(tempStr); userLists.Remove(user); sendUserLists(); userList.Items.Remove(user.userName); break; } } break; } } catch { return; } } }
private void newClientThreadMethod() { while (!isExit) { tcpclient = tcplistener.AcceptTcpClient(); UserClient userclient = new UserClient(tcpclient); Thread userClientThread = new Thread(newUserClientThreadMethod); userClientThread.Start(userclient); } }