gpt4 book ai didi

c# - 客户端套接字未获取.NET中的响应字节

转载 作者:行者123 更新时间:2023-12-03 12:04:28 24 4
gpt4 key购买 nike

我正在服务器套接字上创建和发送消息,但没有得到任何响应,我想知道同样的可能原因。以下是我的客户端套接字示例代码

static void Main()
{
int _DCPport = 9090;
IPHostEntry ipHostInfo = Dns.GetHostEntry("HostName");
Console.WriteLine("Got the IP Host Info" , ipHostInfo.ToString ());
IPAddress ipAddress = ipHostInfo.AddressList[0];
Console.WriteLine("Got the IP hadress Info");

//End point of the host where the socket will be connected
IPEndPoint remoteDAPEndPoint = new IPEndPoint(ipAddress, _DCPport);

// Create a clientSocket that connects to host
Socket clientDAP = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientDAP.Connect(remoteDAPEndPoint);
Console.WriteLine("Client socket connected to remote end point");

#region Input variables
string requestString = "Hello";
string responseString = "";

byte[] requestByte = System.Text.Encoding.UTF8.GetBytes(requestString);
byte[] responseByte = new byte[1024];

StringBuilder messageBuilder = new StringBuilder();
int byteResult = 0;
#endregion

try
{
//sending the string as bytes over the socket
Console.WriteLine("Sending the input " + requestString);
clientDAP.Send(requestByte);
}
catch (SocketException eX)
{

Console.WriteLine(eX.Message);
}

try
{
//recieving the response bytes
byteResult = clientDAP.Receive(responseByte, clientDAP.Available, SocketFlags.None);
Console.WriteLine("Recieved {0} bytes as response from remote end point" , byteResult);
if (clientDAP.Connected)
{
responseString = Encoding.UTF8.GetString(responseByte);
messageBuilder.Append(responseString);
}
}
catch (SocketException eX)
{

Console.WriteLine(eX.Message);
}

clientDAP.Shutdown(SocketShutdown.Both);
clientDAP.Disconnect(true);


string sResult = messageBuilder.ToString();
Console.WriteLine(sResult);


}

我在调用socket.Recieve()时没有收到任何字节,为什么会这样呢?

最佳答案

Socket.Send :

There is also no guarantee that the data you send will appear on the network immediately. To increase network efficiency, the underlying system may delay transmission until a significant amount of outgoing data is collected. A successful completion of the Send method means that the underlying system has had room to buffer your data for a network send



这意味着,当您对 Send的调用完成时,数据甚至可能尚未到达服务器。更不用说服务器有时间来处理您的数据并返回响应了。

但是您的代码直接收费以尝试接收服务器的响应。就其本身而言,这并非不合理。如果您指定了缓冲区的大小,则对 Receive 的调用将一直阻塞,直到收到一些数据为止,而不是使用 Available ,如果没有可用数据,它将很高兴地返回 0。因此,您的 Receive调用最多要求 0字节,这就是您要获得的字节数。

所以换这行
byteResult = clientDAP.Receive(responseByte, 1024, SocketFlags.None);

(或者更好的方法是,引入一个常数和/或使用 responseByte.Length或切换到未明确指定所需字节数的重载)

关于c# - 客户端套接字未获取.NET中的响应字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35032145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com