我一直在编写我的应用程序。我需要它来打开5个不同的TcpListener(五个异步监听器)。我的服务器代码是:
private static void StartServer(int number)
{
while (true)
{
var listener = new TcpListener(WebVars.LocalIp, WebVars.ServerPort + number);
listener.Start();
Console.WriteLine("Server started on port {0}", WebVars.ServerPort + number);
var client = listener.AcceptTcpClient();
Console.WriteLine("** Client connected !");
var netStream = client.GetStream();
byte[] bytes = new byte[client.ReceiveBufferSize];
netStream.Read(bytes, 0, client.ReceiveBufferSize);
string query = Encoding.ASCII.GetString(bytes);
// example query: IP-command-subject-year (last two only if command is "get")
var command = query.Split('-');
Console.WriteLine("Connected client from IP {0}\nCommand: {1}", command[0], command[1]);
if (command[1] == "query") // if the client wants a list of the available subjects
{
var docToSend = XDocument.Load("BagrutSubjects.xml");
byte[] bytesToSend = Encoding.ASCII.GetBytes(docToSend.ToString());
netStream.Write(bytesToSend, 0, bytesToSend.Length); // write the xml in string form
netStream.Close();
client.Close();
continue;
}
if (command[1] == "get")
{
// example of year: 2012a, 2012b (a = summer, b = winter)
string subject = command[2], year = command[3];
if (File.Exists(Path.Combine("subjects", subject, year, "subject.pdf")))
{
// if the pdf exists
}
}
listener.Stop();
}
}
客户端代码是这样的:
if (Variables.IsClient)
{
Console.WriteLine(" -- Bagrut Client -- ");
Console.Write("Enter IP of server to connect to: ");
// ReSharper disable once AssignNullToNotNullAttribute
var ip = IPAddress.Parse(Console.ReadLine());
var client = new TcpClient();
client.Connect(ip, 1002); // the third server.
Console.WriteLine("** Connected to server!");
var bytes = Encoding.ASCII.GetBytes("127.0.0.1-query");
var stream = client.GetStream();
stream.Write(bytes, 0, bytes.Length);
stream.Read(bytes, 0, bytes.Length);
Console.WriteLine("Recieved {0}", Encoding.ASCII.GetString(bytes));
}
我使用静态Thread对象来启动它们,声明如下:
public static Thread serverThread1 = new Thread(() => StartServer(1));
public static Thread serverThread2 = new Thread(() => StartServer(2));
public static Thread serverThread3 = new Thread(() => StartServer(3));
public static Thread serverThread4 = new Thread(() => StartServer(4));
public static Thread serverThread5 = new Thread(() => StartServer(5));
当我启动服务器时,这一切都很顺利(其输出看起来像这样:
)服务器决定变得不稳定并执行此操作:
。在我的代码中没有任何地方说它用换行符向整个控制台发送垃圾邮件。我不知道为什么会这样,服务器也没有响应。客户端没有收到任何东西(它应该是)。我该如何解决这个问题?