Servidor de bate-papo multithreading em C #, identificador de desconexão
Estou procurando uma maneira de lidar com uma desconexão, porque toda vez que fecho um cliente, o servidor para de funcionar. Recebo uma mensagem de erro de que "não é possível ler além do final do fluxo" nesta linha:
string message = reader.ReadString();
Também preciso de uma maneira de excluir o cliente desconectado da lista de clientes. Aqui está o meu código: Servidor
using System;
using System.Threading;
using System.Net.Sockets;
using System.IO;
using System.Net;
using System.Collections.Generic;
namespace Server
{
class Server
{
public static List<TcpClient> clients = new List<TcpClient>();
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
TcpListener ServerSocket = new TcpListener(ip, 14000);
ServerSocket.Start();
Console.WriteLine("Server started.");
while (true)
{
TcpClient clientSocket = ServerSocket.AcceptTcpClient();
clients.Add(clientSocket);
handleClient client = new handleClient();
client.startClient(clientSocket);
}
}
}
public class handleClient
{
TcpClient clientSocket;
public void startClient(TcpClient inClientSocket)
{
this.clientSocket = inClientSocket;
Thread ctThread = new Thread(Chat);
ctThread.Start();
}
private void Chat()
{
while (true)
{
BinaryReader reader = new BinaryReader(clientSocket.GetStream());
while (true)
{
string message = reader.ReadString();
foreach (var client in Server.clients)
{
BinaryWriter writer = new BinaryWriter(client.GetStream());
writer.Write(message);
}
}
}
}
}
}
Cliente
using System;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace Client
{
class Client
{
public static void Write()
{
TcpClient client = new TcpClient("127.0.0.1", 14000);
while (true)
{
string str = Console.ReadLine();
BinaryWriter writer = new BinaryWriter(client.GetStream());
writer.Write(str);
}
}
public static void Read()
{
TcpClient client = new TcpClient("127.0.0.1", 14000);
while (true)
{
BinaryReader reader = new BinaryReader(client.GetStream());
Console.WriteLine(reader.ReadString());
}
}
static void Main(string[] args)
{
Thread Thread = new Thread(Write);
Thread Thread2 = new Thread(Read);
Thread.Start();
Thread2.Start();
}
}
}