从套接字读取网络流
我正在尝试从套接字读取网络流。我知道套接字的地址族是InterNetwork,套接字类型是Stream,协议类型是IP。
我有一个 IPEndPoint,其中包含我尝试读取的 IP 地址和端口。
NetworkStream myNetworkStream;
Socket socket;
IPEndPoint maxPort = new IPEndPoint(IPAddress.Parse("x.x.x.x"), xxxx);
socket =
new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
socket.Connect(maxPort);
myNetworkStream = new NetworkStream(socket);
while (myNetworkStream.DataAvailable == false)
{
Thread.Sleep(1);
}
byte[] buffer = new byte[1024];
int offset = 0;
int count = 1024;
myNetworkStream.Read(buffer, offset, count);
Console.ReadLine();
我知道数据可用(我正在编写自己的现有应用程序版本,并使用源代码作为参考),但 true/false Data Available 属性始终保持 false,并且我从未点击 Console.Readline()。
我在这里做错了什么?
I am trying to read a Network Stream from a socket. I know that the Address Family of the socket is InterNetwork, the Socket Type is Stream and the Protocol Type is IP.
I have an IPEndPoint which consists of the IP address and the port that I am trying to read from.
NetworkStream myNetworkStream;
Socket socket;
IPEndPoint maxPort = new IPEndPoint(IPAddress.Parse("x.x.x.x"), xxxx);
socket =
new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
socket.Connect(maxPort);
myNetworkStream = new NetworkStream(socket);
while (myNetworkStream.DataAvailable == false)
{
Thread.Sleep(1);
}
byte[] buffer = new byte[1024];
int offset = 0;
int count = 1024;
myNetworkStream.Read(buffer, offset, count);
Console.ReadLine();
I know that data is available (I am writing my own version of an existing application and am using the source code as a reference) but the true/false Data Available property always remains false and I never hit my Console.Readline().
What am I doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我创建了一个简单的服务器应用程序并测试了您的客户端代码。这一切对我来说都很好。我建议您查看服务器代码以仔细检查它是否正在向客户端发送数据。您还可以使用数据包嗅探器工具(例如 WireShark)来验证数据是否正在传输。
这是我的服务器代码:
如果您的服务器正在返回数据,您可能需要检查 TCP 标头。问题可能是由于未设置 PSH 位。这将导致 TCP 堆栈无法发出数据可用的信号。我之所以这么想,是因为您说
Read
调用不会返回,并且DataAvailable
不断返回 false。希望这有帮助。
I created a simple server application and tested your client code out. It all works fine for me. I would suggest you look at the server code to double check that it is sending data to the client. You could also use a packet sniffer tool such as WireShark to verify data is being transmitted as well.
Here is my server code:
If your server is returning data, you may want to check the TCP headers. The problem might be from the PSH bit not being set. This would cause the TCP stack to not signal up that data is available yet. I am thinking this from the fact that you said
Read
call doesn't return andDataAvailable
returns false continually.Hope this helps.