【发布时间】:2016-10-02 18:27:08
【问题描述】:
我正在用 C# 制作聊天应用程序。所以我需要帮助来让 tcp 服务器不间断地工作。当我在服务器上发送消息时它正在接收它但随后停止并且没有收到另一条消息...
try
{
IPAddress ipAd = IPAddress.Parse("127.0.0.1");
TcpListener myList = new TcpListener(ipAd, 8001);
myList.Start();
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recieved...");
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The message was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
Console.ReadLine();
// s.Close();
//myList.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
【问题讨论】:
-
你需要在一个循环中进行异步套接字操作。
标签: c# visual-studio chat tcpserver