【发布时间】:2016-01-26 19:32:47
【问题描述】:
每当客户端断开连接时,服务器就会崩溃。这是服务器的代码
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Threading;
namespace C_Sharp_Testting
{
class Server
{
private static TcpListener tcpListener;
private static List<TcpClient> tcpClientsList = new List<TcpClient>();
static void Main(string[] args)
{
tcpListener = new TcpListener(IPAddress.Any, 1234);
tcpListener.Start();
Console.WriteLine("Server started");
while (true)
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
tcpClientsList.Add(tcpClient);
Thread thread = new Thread(ClientListener);
thread.Start(tcpClient);
}
}
public static void ClientListener(object obj)
{
TcpClient tcpClient = (TcpClient)obj;
StreamReader reader = new StreamReader(tcpClient.GetStream());
Console.WriteLine("Client connected");
while (true)
{
string message = reader.ReadLine();
BroadCast(message, tcpClient);
Console.WriteLine(">>> "+message);
}
}
public static void BroadCast(string msg, TcpClient excludeClient)
{
foreach (TcpClient client in tcpClientsList)
{
if (client != excludeClient)
{
StreamWriter sWriter = new StreamWriter(client.GetStream());
sWriter.WriteLine(">>> "+msg);
sWriter.Flush();
}
}
}
}
}
我已经尝试关闭 reader 和 tcpClient,但都没有工作。
【问题讨论】:
标签: c# sockets tcpclient tcplistener