.NET 2.x Многопользовательский чат на TcpClient - C#
Формулировка задачи:
Решил написать чат.
сервер:
Клиент:
Проблема в том что при подключении нового клиента в списке users все перезаписывается им((((
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Net.Sockets; using System.Net; using System.Runtime.InteropServices; namespace ConsoleApplication1 { class Program { const int port=3128; public static List<user> users = new List<user>(); public static user tmpuser = new user(); public static TcpListener listener; public static Thread conn; static bool doneserver; public static string host = Dns.GetHostName(); public static string myIp = Dns.GetHostByName(host).AddressList[0].ToString(); static void Main(string[] args) { IPAddress localhost = IPAddress.Parse(myIp); listener = new TcpListener(localhost, port); listener.Start(); Console.WriteLine("Сервер запущен...\r\n"); conn = new Thread(connection); conn.Start(); } static string ReadMessage(TcpClient client) { byte[] buffer = new byte[256]; int totalRead = 0; do { int read = client.GetStream().Read(buffer, totalRead, buffer.Length - totalRead); totalRead += read; } while (client.GetStream().DataAvailable); return Encoding.Unicode.GetString(buffer, 0, totalRead); } public static void connection() { doneserver = false; Thread thread; while (!doneserver) { TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("Клиент подключен. IP:{0}",client.Client.RemoteEndPoint.ToString()); thread = new Thread(new ParameterizedThreadStart(HandledientThread)); thread.Start(client); } } static void HandledientThread(object obj) { TcpClient clientid = obj as TcpClient; bool done = false; while (!done) { string message = ReadMessage(clientid); string flag = ""; string mess = ""; flag += message[0]; //////////////если прислал сообщение//////// if (flag == "m") { Console.WriteLine("log::m::{0}",message); for (int i = 1; i < message.Length; i++) { mess += message[i]; } Console.WriteLine(mess); SendMessageAll(clientid, mess, "m"); } //////////////если прислал ник/////////////// if (flag == "n") { for (int i = 1; i < message.Length; i++) { mess += message[i]; } tmpuser.add(mess, clientid); users.Add(tmpuser); SendMessageAll(clientid, mess, "a"); mess = ""; Console.WriteLine("//////////////////////////////////////"); foreach (user tmp in users) { Console.Write("name:{0}",tmp.name); Console.WriteLine("klient:{0}", tmp.klient.Client.RemoteEndPoint.ToString()); if(clientid!=tmp.klient) mess += tmp.name + ";"; } Console.WriteLine("///////////////////////////////////////"); Console.Write("log:::n:::{0}", mess); SendMessage(clientid, mess, "l"); } ///////////////если отключился///////////// if (flag == "o") { Console.WriteLine("log::o::{0}", message); for (int i = 1; i < message.Length; i++) { mess += message[i]; } SendMessageAll(clientid,mess, "z"); user tmp2 = new user(); foreach (user tmp in users) { if (tmp.klient == clientid) { tmp2.add(tmp.name, tmp.klient); } } users.Remove(tmp2); done = true; } } Console.WriteLine("Клиент отключен. IP:{0}",clientid.Client.RemoteEndPoint); clientid.Close(); } static void SendMessage(TcpClient client, string message, string flag) { flag += message; byte[] bytes = Encoding.Unicode.GetBytes(flag); client.GetStream().Write(bytes, 0, bytes.Length); } static void SendMessageAll(TcpClient client, string message, string flag) { flag += message; byte[] bytes = Encoding.Unicode.GetBytes(flag); foreach (user tmp in users) { if (tmp.klient!=client) tmp.klient.GetStream().Write(bytes, 0, bytes.Length); } } } public class user { public int id; public string name; public TcpClient klient; public void add(int aid, string aname, TcpClient aklient) { id = aid; name = aname; klient = aklient; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Net; using System.Threading; using System.Runtime.Serialization.Formatters.Binary; namespace Внутреняя_ICQ_Клиент_ { public partial class Form1 : Form { IPAddress ipserver; int port; TcpClient clientkl; Thread read; public string NIK; public Form1() { InitializeComponent(); } private void пользователиВСетиToolStripMenuItem_Click(object sender, EventArgs e) { if (textBox1.Text != "") { NIK = textBox1.Text; ipserver=IPAddress.Parse(textBox2.Text.ToString()); port=Convert.ToInt32(textBox5.Text); if (пользователиВСетиToolStripMenuItem.Text == "Подключиться") { пользователиВСетиToolStripMenuItem.Text = "Отключиться"; ///////вкладки/////////////// panelmessage.Visible = true; panellogin.Visible = false; panelconfig.Visible=false; ///////////////////////////// try { clientkl = new TcpClient(); clientkl.Connect(ipserver, port); SendMessage(clientkl, NIK, "n"); read = new Thread(new ParameterizedThreadStart(Read)); read.Start(clientkl); } catch { MessageBox.Show("[X] Сервер не доступен!"); пользователиВСетиToolStripMenuItem.Text = "Подключиться"; ///////вкладки/////////////// panelmessage.Visible = false; panellogin.Visible = true; panelconfig.Visible = false; ///////////////////////////// //read.Abort(); clientkl.Close(); } } else { ///////вкладки/////////////// panelmessage.Visible = false; panellogin.Visible = true; panelconfig.Visible=false; ///////////////////////////// пользователиВСетиToolStripMenuItem.Text = "Подключиться"; SendMessage(clientkl, NIK, "o"); } } else { ///////вкладки/////////////// panelmessage.Visible = false; panellogin.Visible = true; panelconfig.Visible = false; ///////////////////////////// MessageBox.Show("Введите НИК"); textBox1.Focus(); } } private void настройкиToolStripMenuItem_Click(object sender, EventArgs e) { ///////вкладки/////////////// panelmessage.Visible = false; panellogin.Visible = false; panelconfig.Visible = true; ///////////////////////////// } private static void SendMessage(TcpClient client, string message, string flag) { flag += message; byte[] bytes = Encoding.Unicode.GetBytes(flag); client.GetStream().Write(bytes, 0, bytes.Length); } public void Read(object obj) { TcpClient client = obj as TcpClient; bool done = false; while (!done) { try { string message = ReadResponse(client); string flag = ""; string mess = ""; flag += message[0]; //////////////если сообщение///////////// if (flag == "m") { richTextBox1.Text += "log: " + message + "\r\n"; for (int i = 1; i < message.Length; i++) { mess += message[i]; } richTextBox1.Text += mess + "\r\n"; } ///////////////если список///////////// if (flag == "l") { richTextBox1.Text += "log: " + message + "\r\n"; for (int i = 1; i < message.Length; i++) { if (message[i] != ';') { mess += message[i]; } else { listBox1.Items.Add(mess); mess = ""; } } } //////////////////если ушел кто-то//////////// if (flag == "z") { richTextBox1.Text += "log: " + message + "\r\n"; for (int i = 1; i < message.Length; i++) { mess += message[i]; } listBox1.Items.Remove(mess); } ///////////////////если пришел кто-то//////////////// if (flag == "a") { richTextBox1.Text += "log: " + message + "\r\n"; for (int i = 1; i < message.Length; i++) { mess += message[i]; } listBox1.Items.Add(mess); } } catch { } } client.Close(); } private static string ReadResponse(TcpClient clientkl) { byte[] buffer = new byte[256]; int totalRead = 0; do { int read = clientkl.GetStream().Read(buffer, totalRead, buffer.Length - totalRead); totalRead += read; } while (clientkl.GetStream() .DataAvailable) ; return Encoding.Unicode.GetString(buffer, 0, totalRead); } private void button2_Click(object sender, EventArgs e) { string message = textBox3.Text; SendMessage(clientkl,message,"m"); richTextBox1.Text += DateTime.Now.ToLongTimeString() + " " + NIK + ": " + message + "\r\n"; textBox3.Text = ""; } private void Form1_Load(object sender, EventArgs e) { } } }
Решение задачи: «.NET 2.x Многопользовательский чат на TcpClient»
textual
Листинг программы
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Net.Sockets; using System.Net; using System.Runtime.InteropServices; namespace ConsoleApplication1 { class Program { const int port=3128; static public List<user> users = new List<user>(); public static TcpListener listener; public static string host = Dns.GetHostName(); public static string myIp = Dns.GetHostByName(host).AddressList[0].ToString(); static void Main(string[] args) { IPAddress localhost = IPAddress.Parse(myIp); listener = new TcpListener(localhost, port); listener.Start(); Console.WriteLine("Сервер запущен..."); Thread thread; while (true) { while (!listener.Pending()) { Thread.Sleep(500); } TcpClient client = new TcpClient(); client =listener.AcceptTcpClient(); thread = new Thread(new ParameterizedThreadStart(wordclient)); thread.Start(client); } } static void wordclient(object obj) { TcpClient clientid = obj as TcpClient; bool done = true; while (done) { string message = ReadMessage(clientid); string flag = ""; string mess = ""; flag += message[0]; //////////////если прислал сообщение//////// if (flag == "m") { for (int i = 1; i < message.Length; i++) { mess += message[i]; } //Console.WriteLine(mess); SendMessageAll(clientid, mess, "m"); } //////////////если прислал ник/////////////// if (flag == "n") { for (int i = 1; i < message.Length; i++) { mess += message[i]; } var tmpuser = new user(); tmpuser.add(mess, clientid); users.Add(tmpuser); SendMessageAll(clientid, mess, "a"); mess = ""; foreach (user tmp in users) { Console.WriteLine("Клиент подключен. IP:{0} Ник:{1}", clientid.Client.RemoteEndPoint.ToString(), tmp.name); if(clientid!=tmp.klient) mess += tmp.name + ";"; } SendMessage(clientid, mess, "l"); } ///////////////если отключился///////////// if (flag == "o") { for (int i = 1; i < message.Length; i++) { mess += message[i]; } SendMessageAll(clientid, mess, "z"); Console.WriteLine("Клиент отключен. IP:{0} Ник:{1}", clientid.Client.RemoteEndPoint, mess); user tmp2 = new user(); foreach (user tmp in users) { if (tmp.klient == clientid) { tmp2.add(tmp.name, tmp.klient); } } users.Remove(tmp2); done = false; } } clientid.Close(); } static string ReadMessage(TcpClient client) { byte[] buffer = new byte[256]; int totalRead = 0; do { int read = client.GetStream().Read(buffer, totalRead, buffer.Length - totalRead); totalRead += read; } while (client.GetStream().DataAvailable); return Encoding.Unicode.GetString(buffer, 0, totalRead); } static void SendMessage(TcpClient client, string message, string flag) { flag += message; byte[] bytes = Encoding.Unicode.GetBytes(flag); client.GetStream().Write(bytes, 0, bytes.Length); } static void SendMessageAll(TcpClient client, string message, string flag) { flag += message; byte[] bytes = Encoding.Unicode.GetBytes(flag); foreach (user tmp in users) { if (tmp.klient!=client) tmp.klient.GetStream().Write(bytes, 0, bytes.Length); } } } public class user { public string name; public TcpClient klient; public void add(string aname, TcpClient aklient) { name = aname; klient = aklient; } } }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д