.NET 3.x Чат TCP Консоль сервер + WinForm клиент - C#
Формулировка задачи:
Чат TCP сервер консоль + WinForm клиент
Есть код где Консоль сервер+ Консоль клиент создает Чат
но когда это я перевел на Консоль сервер+ WinForm клиент
возникает проблема , при отправки через клиент сообщения
цикл стает бесконечен к зависанию , как и в WinForm клиент
что не хватает в коде этом ?
Консоль сервер Winform_Winform_Chat
файл Program.cs
Обьект ServerObject.cs к Консоль серверу
Обьект ClientObject.cs к Консоль серверу
И так же
WinForm клиент Winform_Winform_Chat
файл Form1.cs
Вот и архив с этим примером
Суть такая что на консоли клиента и сервера этот пример работает
как только код перегнать на сервер, и Winform клиент то пример не работает, циклиться к зависанию
явно что то не хватает , я пробывал решить, но не получилось ходил по кругу , как не крути не получаеться
Надеюсь кто то знает , то его не хватает в этом коде товарищи?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Server_chat;
namespace Winform_Winform_Chat
{
class Program
{
static ServerObject server; // сервер
static Thread listenThread; // потока для прослушивания
static void Main(string[] args)
{
Title_Console("Сервер Чат v 1.0");
try
{
server = new ServerObject();
listenThread = new Thread(new ThreadStart(server.Listen));
listenThread.Start(); //старт потока
}
catch (Exception ex)
{
server.Disconnect();
Console.WriteLine(ex.Message);
}
}
static void Title_Console(string title)
{
Console.BackgroundColor = ConsoleColor.DarkCyan;
Console.Clear();
Console.ForegroundColor = ConsoleColor.White;
Console.Title = title;
}
static void Pause()
{
Console.ReadKey(true);
}
static void Error_msg(string msg)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(msg);
Console.ForegroundColor = ConsoleColor.White;
}
}
}using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Server_chat
{
class ServerObject
{
static TcpListener tcpListener; // сервер для прослушивания
List<ClientObject> clients = new List<ClientObject>(); // все подключения
protected internal void AddConnection(ClientObject clientObject)
{
clients.Add(clientObject);
}
protected internal void RemoveConnection(string id)
{
// получаем по id закрытое подключение
ClientObject client = clients.FirstOrDefault(c => c.Id == id);
// и удаляем его из списка подключений
if (client != null)
clients.Remove(client);
}
// прослушивание входящих подключений
protected internal void Listen()
{
try
{
tcpListener = new TcpListener(IPAddress.Any, 8888);
tcpListener.Start();
Console.WriteLine("Сервер запущен. Ожидание подключений...");
while (true)
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
ClientObject clientObject = new ClientObject(tcpClient, this);
Thread clientThread = new Thread(new ThreadStart(clientObject.Process));
clientThread.Start();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Disconnect();
}
}
// трансляция сообщения подключенным клиентам
protected internal void BroadcastMessage(string message, string id)
{
byte[] data = Encoding.Unicode.GetBytes(message);
for (int i = 0; i < clients.Count; i++)
{
if (clients[i].Id != id) // если id клиента не равно id отправляющего
{
clients[i].Stream.Write(data, 0, data.Length); //передача данных
}
}
}
// отключение всех клиентов
protected internal void Disconnect()
{
tcpListener.Stop(); //остановка сервера
for (int i = 0; i < clients.Count; i++)
{
clients[i].Close(); //отключение клиента
}
Environment.Exit(0); //завершение процесса
}
}
}using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
namespace Server_chat
{
class ClientObject
{
protected internal string Id { get; private set; }
protected internal NetworkStream Stream { get; private set; }
string userName;
TcpClient client;
ServerObject server; // объект сервера
public ClientObject(TcpClient tcpClient, ServerObject serverObject)
{
Id = Guid.NewGuid().ToString();
client = tcpClient;
server = serverObject;
serverObject.AddConnection(this);
}
public void Process()
{
try
{
Stream = client.GetStream();
// получаем имя пользователя
string message = GetMessage();
userName = message;
message = userName + " вошел в чат";
// посылаем сообщение о входе в чат всем подключенным пользователям
server.BroadcastMessage(message, this.Id);
Console.WriteLine(message);
// в бесконечном цикле получаем сообщения от клиента
while (true)
{
try
{
message = GetMessage();
message = String.Format("{0}: {1}", userName, message);
Console.WriteLine(message);
break;
server.BroadcastMessage(message, this.Id);
Console.ReadKey(true);
//break;
}
catch
{
message = String.Format("{0}: покинул чат", userName);
Console.WriteLine(message);
server.BroadcastMessage(message, this.Id);
break;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
// в случае выхода из цикла закрываем ресурсы
server.RemoveConnection(this.Id);
Close();
}
}
// чтение входящего сообщения и преобразование в строку
private string GetMessage()
{
byte[] data = new byte[64]; // буфер для получаемых данных
StringBuilder builder = new StringBuilder();
int bytes = 0;
do
{
bytes = Stream.Read(data, 0, data.Length);
builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
}
while (Stream.DataAvailable);
return builder.ToString();
}
// закрытие подключения
protected internal void Close()
{
if (Stream != null)
Stream.Close();
if (client != null)
client.Close();
}
}
}using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace Client_Winform
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static string userName;
private const string host = "127.0.0.1";
private const int port = 8888;
static TcpClient client;
static NetworkStream stream;
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
client = new TcpClient();
try
{
client.Connect(host, port); //подключение клиента
stream = client.GetStream(); // получаем поток
string message = textBox1.Text;
byte[] data = Encoding.Unicode.GetBytes(message);
stream.Write(data, 0, data.Length);
//// запускаем новый поток для получения данных
Thread receiveThread = new Thread(new ThreadStart(ReceiveMessage));
receiveThread.Start(); //старт потока
//Console.WriteLine("Добро пожаловать, {0}", userName);
SendMessage();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Disconnect();
}
}
// отправка сообщений
private void SendMessage()
{
while (true)
{
//Console.Write("Введите сообщение: ");
//string message = Console.ReadLine();
byte[] data = Encoding.Unicode.GetBytes(textBox1.Text);
stream.Write(data, 0, data.Length);
}
}
// получение сообщений
private void ReceiveMessage()
{
while (true)
{
try
{
byte[] data = new byte[64]; // буфер для получаемых данных
StringBuilder builder = new StringBuilder();
int bytes = 0;
do
{
bytes = stream.Read(data, 0, data.Length);
builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
}
while (stream.DataAvailable);
string message = builder.ToString();
richTextBox1.AppendText(message);
//Console.WriteLine(message + "\n");//вывод сообщения
}
catch
{
Console.WriteLine("Подключение прервано!"); //соединение было прервано
Console.ReadLine();
Disconnect();
}
}
}
static void Disconnect()
{
if (stream != null)
stream.Close();//отключение потока
if (client != null)
client.Close();//отключение клиента
//Environment.Exit(0); //завершение процесса
}
}
}Решение задачи: «.NET 3.x Чат TCP Консоль сервер + WinForm клиент»
textual
Листинг программы
listBox1.Items.Add(GetMessage());