0

我的客户端 c# 套接字与 java 服务器套接字通信时遇到问题。当我尝试阅读响应时,问题就出现了。我的代码是这样的:

IPHostEntry IPHost = Dns.Resolve("IP_ADDRESS");
Console.WriteLine(IPHost.HostName);
string []aliases = IPHost.Aliases; 
IPAddress[] addr = IPHost.AddressList;
Console.WriteLine(addr[0]);
EndPoint ep = new IPEndPoint(addr[0],1024); 
Socket sock =
   new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
sock.Connect(ep);
if(sock.Connected)
   Console.WriteLine("OK");
Encoding ASCII = Encoding.ASCII;
string Get = "A";
Byte[] ByteGet = ASCII.GetBytes(Get);
Byte[] RecvBytes = new Byte[256];
sock.Send(ByteGet, ByteGet.Length, 0);
Int32 bytes = sock.Receive(RecvBytes, RecvBytes.Length, 0);
Console.WriteLine(bytes);
String strRetPage = null;
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
while( bytes > 0 ) {
   bytes = sock.Receive(RecvBytes, RecvBytes.Length, 0);
   strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
   Console.WriteLine(strRetPage );
}
sock.Close();

在代码行

Int32 bytes = sock.Receive(RecvBytes, RecvBytes.Length, 0);

我的客户挂起。我必须停止应用程序。似乎不响应套接字服务器。套接字服务器的具体做法是发送和接收 BitStream。

4

1 回答 1

1

如果没有服务器的 Java 代码,很难判断,但您的服务器似乎很可能没有发送预期的 256 字节。由于默认情况下 Socket.Receive 是阻塞的,因此客户端会一直等待数据。

于 2012-10-22T07:56:26.140 回答