我正在使用TCP连接,其中我的客户端通过2个不同的端口连接到服务器的IP。因此,我有2个TcpClient对象实例,一个实例连接到端口9000上的IP,另一个实例连接到端口9001上。
2个连接的目的是服务器使用端口9000上的活动连接向客户端频繁发出某些响应,并且客户端使用这些响应在端口9001上形成并发送请求。
现在,我第一次连接9000时,我得到一个响应,然后我提出一个请求并通过9001解除。端口,但我想不出另一种方法:
IPAddress IPAddress = IPAddress.Parse("192.168.1.10");
public static async Task ConnectToPort9000()
{
TcpClient TcpClient1 = new TcpClient();
try
{
await TcpClient1.ConnectAsync(IPAddress, 9000);
if (TcpClient1.Connected)
{
byte[] Buffer = new byte[1024];
while (await TcpClient1.GetStream().ReadAsync(Buffer, 0, Buffer.Length) > 0)
{
//Server returns a message on this port
string Port9000Response = Encoding.UTF8.GetString(Buffer, 0, Buffer.Length);
//Setting ConfigureAwait(false) so that any further responses returned
//on this port can be dealt with
await Task.Run(async () =>
{
await SendRequestToPort9001BasedOnResponseAsync(Port9000Response);
}).ConfigureAwait(false);
}
}
}
catch (Exception)
{
throw;
}
}
private async Task SendRequestToPort9001BasedOnResponseAsync(string Port9000Response)
{
//Open connection on port 9001 and send request
TcpClient TcpClient2 = new TcpClient();
await TcpClient2.ConnectAsync(IPAddress, 9001);
if (TcpClient2.Connected)
{
//Handle each string response differently
if (Port9000Response == "X")
{
//Form a new request message to send on port 9001
string _NewRequestMesssage = "Y";
byte[] RequestData = Encoding.UTF8.GetBytes(_NewRequestMesssage);
new SocketAsyncEventArgs().SetBuffer(RequestData, 0, RequestData.Length);
await TcpClient2.GetStream().WriteAsync(RequestData, 0, RequestData.Length);
await TcpClient2.GetStream().FlushAsync();
//Handle any responses on this port
//At this point, based on the request message sent on this port 9001
//server sends another response on **port 9000** that needs separately dealing with
//so the while condition in the previous method should receive a response and continue handling that response again
}
else if (Port9000Response == "A")
{
//Do something else
}
}
}
目前,我遇到的问题是,在端口9001上发送请求后,在端口9001上处理任何响应消息时,服务器已经在端口9000上发送了响应,但是我的while循环使用第一种方法没有被触发,这似乎是因为它仍在执行第二种方法来处理端口9001上的请求/响应。我尝试使用ConfigureAwait(false)基本上是fire and忘记,但似乎没有工作。我是否以错误的方式处理异步流程?还是应该考虑采取其他措施,例如行动/代表?
2个连接的目的是服务器使用端口9000上的活动连接频繁向客户端提供某些响应,而客户端使用这些响应在端口9001上形成并发送请求。
请不要这样做。套接字编程足够困难,而不会因多个连接而变得极其复杂。错误处理变得更加困难,半开连接的检测变得更加困难(或不可能),并且通信死锁也难以避免。
每个套接字连接已经是双向的;它已经有两个独立的流。您唯一需要做的就是始终阅读并根据需要发送。读写流是独立的,因此请保持读写独立。