我正在学习c#套接字编程。所以,我决定进行TCP聊天,基本的想法是A客户端将数据发送到服务器,然后服务器在线为所有客户端广播它(在这种情况下,所有客户端都在字典中)。
当连接了1个客户端时,它按预期工作,当连接的客户端超过1个时,就会出现问题。
服务器
class Program
{
static void Main(string[] args)
{
Dictionary<int,TcpClient> list_clients = new Dictionary<int,TcpClient> ();
int count = 1;
TcpListener ServerSocket = new TcpListener(IPAddress.Any, 5000);
ServerSocket.Start();
while (true)
{
TcpClient client = ServerSocket.AcceptTcpClient();
list_clients.Add(count, client);
Console.WriteLine("Someone connected!!");
count++;
Box box = new Box(client, list_clients);
Thread t = new Thread(handle_clients);
t.Start(box);
}
}
public static void handle_clients(object o)
{
Box box = (Box)o;
Dictionary<int, TcpClient> list_connections = box.list;
while (true)
{
NetworkStream stream = box.c.GetStream();
byte[] buffer = new byte[1024];
int byte_count = stream.Read(buffer, 0, buffer.Length);
byte[] formated = new Byte[byte_count];
//handle the null characteres in the byte array
Array.Copy(buffer, formated, byte_count);
string data = Encoding.ASCII.GetString(formated);
broadcast(list_connections, data);
Console.WriteLine(data);
}
}
public static void broadcast(Dictionary<int,TcpClient> conexoes, string data)
{
foreach(TcpClient c in conexoes.Values)
{
NetworkStream stream = c.GetStream();
byte[] buffer = Encoding.ASCII.GetBytes(data);
stream.Write(buffer,0, buffer.Length);
}
}
}
class Box
{
public TcpClient c;
public Dictionary<int, TcpClient> list;
public Box(TcpClient c, Dictionary<int, TcpClient> list)
{
this.c = c;
this.list = list;
}
}
我创建了这个框,所以我可以为Thread.start()
传递2个参数。
客户端:
class Program
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
int port = 5000;
TcpClient client = new TcpClient();
client.Connect(ip, port);
Console.WriteLine("client connected!!");
NetworkStream ns = client.GetStream();
string s;
while (true)
{
s = Console.ReadLine();
byte[] buffer = Encoding.ASCII.GetBytes(s);
ns.Write(buffer, 0, buffer.Length);
byte[] receivedBytes = new byte[1024];
int byte_count = ns.Read(receivedBytes, 0, receivedBytes.Length);
byte[] formated = new byte[byte_count];
//handle the null characteres in the byte array
Array.Copy(receivedBytes, formated, byte_count);
string data = Encoding.ASCII.GetString(formated);
Console.WriteLine(data);
}
ns.Close();
client.Close();
Console.WriteLine("disconnect from server!!");
Console.ReadKey();
}
}
答案 0 :(得分:6)
从您的问题中不清楚具体您遇到的问题。但是,检查代码会发现两个重要问题:
以下是解决这两个问题的代码版本:
服务器代码:
class Program
{
static readonly object _lock = new object();
static readonly Dictionary<int, TcpClient> list_clients = new Dictionary<int, TcpClient>();
static void Main(string[] args)
{
int count = 1;
TcpListener ServerSocket = new TcpListener(IPAddress.Any, 5000);
ServerSocket.Start();
while (true)
{
TcpClient client = ServerSocket.AcceptTcpClient();
lock (_lock) list_clients.Add(count, client);
Console.WriteLine("Someone connected!!");
Thread t = new Thread(handle_clients);
t.Start(count);
count++;
}
}
public static void handle_clients(object o)
{
int id = (int)o;
TcpClient client;
lock (_lock) client = list_clients[id];
while (true)
{
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int byte_count = stream.Read(buffer, 0, buffer.Length);
if (byte_count == 0)
{
break;
}
string data = Encoding.ASCII.GetString(buffer, 0, byte_count);
broadcast(data);
Console.WriteLine(data);
}
lock (_lock) list_clients.Remove(id);
client.Client.Shutdown(SocketShutdown.Both);
client.Close();
}
public static void broadcast(string data)
{
byte[] buffer = Encoding.ASCII.GetBytes(data + Environment.NewLine);
lock (_lock)
{
foreach (TcpClient c in list_clients.Values)
{
NetworkStream stream = c.GetStream();
stream.Write(buffer, 0, buffer.Length);
}
}
}
}
客户代码:
class Program
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
int port = 5000;
TcpClient client = new TcpClient();
client.Connect(ip, port);
Console.WriteLine("client connected!!");
NetworkStream ns = client.GetStream();
Thread thread = new Thread(o => ReceiveData((TcpClient)o));
thread.Start(client);
string s;
while (!string.IsNullOrEmpty((s = Console.ReadLine())))
{
byte[] buffer = Encoding.ASCII.GetBytes(s);
ns.Write(buffer, 0, buffer.Length);
}
client.Client.Shutdown(SocketShutdown.Send);
thread.Join();
ns.Close();
client.Close();
Console.WriteLine("disconnect from server!!");
Console.ReadKey();
}
static void ReceiveData(TcpClient client)
{
NetworkStream ns = client.GetStream();
byte[] receivedBytes = new byte[1024];
int byte_count;
while ((byte_count = ns.Read(receivedBytes, 0, receivedBytes.Length)) > 0)
{
Console.Write(Encoding.ASCII.GetString(receivedBytes, 0, byte_count));
}
}
}
注意:
lock
语句确保list_clients
对象的线程独占访问。Box
个对象。集合本身由所有执行的方法都可访问的静态字段引用,并且分配给每个客户端的int
值作为线程参数传递,因此线程可以查找相应的客户端对象。0
完成的读取操作。这是用于指示远程端点已完成发送的标准套接字信号。端点表示已使用Shutdown()
方法完成发送。为了启动正常关闭,使用&#34; send&#34;来调用Shutdown()
。原因,表明端点已停止发送,但仍会收到。另一个端点,一旦完成发送到第一个端点,就可以调用Shutdown()
,原因是&#34;两者都是&#34;表示已完成发送和接收。代码中仍存在各种问题。以上仅解决了最明显的问题,并将代码带到了一个非常基本的服务器/客户端架构的工作演示的合理传真中。
的附录:强>
一些补充说明,以解决评论中的后续问题:
Thread.Join()
(即等待该线程退出),以确保在启动正常关闭过程后,它实际上不会关闭套接字直到远程端点通过关闭其结束来响应。o => ReceiveData((TcpClient)o)
作为ParameterizedThreadStart
委托是我更喜欢铸造线程参数的习惯用法。它允许线程入口点保持强类型。虽然,那段代码并不完全是我通常会写的;我紧紧抓住你的原始代码,同时仍然利用这个机会来说明这个成语。但实际上,我会使用无参数ThreadStart
委托来使用构造函数重载,并让lambda表达式捕获必要的方法参数:Thread thread = new Thread(() => ReceiveData(client)); thread.Start();
然后,根本不需要进行转换(如果有任何参数)是值类型,它们的处理没有任何装箱/拆箱开销...在这种情况下通常不是一个关键问题,但仍然让我感觉更好:))。Control.Invoke()
(或Dispatcher.Invoke()
);更复杂(和恕我直言,更优秀)的方法是使用async
/ await
进行I / O.如果您使用StreamReader
来接收数据,那么该对象已经具有等待的ReadLineAsync()
和类似的方法。如果直接使用Socket
,您可以使用Task.FromAsync()
方法将BeginReceive()
和EndReceive()
方法包装在等待中。无论哪种方式,结果是当I / O异步发生时,仍然可以在UI线程中处理完成,您可以在其中直接访问UI对象。 (在这种方法中,您将等待代表接收代码的任务,而不是使用Thread.Join()
,以确保您不会过早关闭套接字。)