我创建了与TCP服务器进行通信的类,如下所示:
public class Tcp_client_server_communication
{
private static TcpClient client;
private static String response = String.Empty;
public void Initialize(string ip, int port)
{
client = new TcpClient(ip, port);
}
public string BeginRead()
{
var buffer = new byte[16];
var ns = client.GetStream();
ns.BeginRead(buffer, 0, buffer.Length, EndRead, buffer);
}
public void EndRead(IAsyncResult result)
{
var buffer = (byte[])result.AsyncState;
var ns = client.GetStream();
var bytesAvalible = ns.EndRead(result);
MessageBox.Show(Encoding.ASCII.GetString(buffer));
BeginRead();
}
}
要调用这些方法,我使用:.Initialize();
.BeginRead();
它的工作正常,但我想以多行TextBox
而不是以MessageBox
的形式显示来自服务器的每条消息。我怎样才能做到这一点?
最佳答案
好了,您可以创建一个List对象来保存所有传递的消息,然后设置一个Timer来经常检查一次是否已将列表添加到其中。在将消息添加到文本框中后,从列表中删除您在每个刻度上阅读的内容。
这个项目要比那时复杂一些,但这是我在中学时期从事的一个老项目:https://github.com/Taloreal/Server-Essentials
关于c# - 异步客户端套接字C#。如何在不阻止程序运行的情况下循环等待来自服务器的信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63916590/