using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Test.Socket
{
public class Server
{
List<Thread> WorkListenerThread;
TcpListener Listener;
public Server()
{
WorkListenerThread = new List<Thread>();
}
public void Start()
{
try
{
Listener = new TcpListener(IPAddress.Any, 12345);
Listener.Start();
StartTCPClientListener();
}
catch (Exception) { }
}
private void StartTCPClientListener()
{
Listener.BeginAcceptTcpClient(new AsyncCallback(HandleTCPClientConnection), null);
}
private void HandleTCPClientConnection(IAsyncResult ar)
{
// Problem 1: after the first connection i have a high cpu load
try
{
TcpClient client = Listener.EndAcceptTcpClient(ar);
Thread clientThread = new Thread(Communicator.CreateConnection);
clientThread.Start(client);
WorkListenerThread.Add(clientThread);
StartTCPClientListener(); // Next client
}
catch (Exception) { }
}
public void Stop()
{
foreach (Thread th in WorkListenerThread)
if (th.IsAlive)
th.Abort();
// Problem 2: Exception because the "HandleTCPClientConnection" get a wrong IAsyncResult
if (Listener != null)
Listener.Stop();
}
}
}
我的客户班。
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using JsonExSerializer;
namespace Test.Socket
{
class Communicator
{
private TcpClient TcpClient = null;
private NetworkStream Stream = null;
private Communicator(TcpClient client)
{
TcpClient = client;
Stream = TcpClient.GetStream();
StartCommunication();
}
public static void CreateConnection(object c)
{
new Communicator(c as TcpClient);
}
private void StartCommunication()
{
string message; // The message
int bytesRead; // Message length
byte[] buffer = new byte[512]; // buffer
while (true)
{
message = String.Empty;
do
{
bytesRead = Stream.Read(buffer, 0, buffer.Length);
message += Encoding.Default.GetString(buffer, 0, bytesRead);
} while (!message.EndsWith("\r\n.\r\n"));
Send("OK", Stream);
}
}
protected void Send(string message, NetworkStream clientStream)
{
byte[] temp = Encoding.Default.GetBytes(message);
clientStream.Write(temp, 0, temp.Length);
clientStream.Flush();
}
}
}
我不知道什么是错的 - .-
有人知道如果客户端断开连接我怎么能检测到? 那也不错。
但是修复高CPU负载会非常好。
答案 0 :(得分:6)
我猜这里的主要问题是:
while (true)
{
message = String.Empty;
do
{
bytesRead = Stream.Read(buffer, 0, buffer.Length);
message += Encoding.Default.GetString(buffer, 0, bytesRead);
} while (!message.EndsWith("\r\n.\r\n"));
Send("OK", Stream);
}
您应该检查此bytesRead
是否为非正数;如果是,那就是流的结束,你应该终止:永远不会有 ,但是你正处于一个紧密的循环中,永远地附加空字符串。
然而!更大的问题是这种方法:每个客户端的线程根本不会扩展,并且不当人们提到“异步IO”时,他们的意思是什么。
我还会说,有一个构造函数启动一个长时间运行的操作(因此不返回)是一个可怕的事情。