[英].NET Socket.Receive() Not Receiving Large Data Streams from Java SocketServer
[英]Java SocketServer is accepting input from a Socket client but the Socket client is not receiving input from the SocketServer
我正在尝试学习Java网络编程,但是遇到了一些障碍。 我已经写了一个服务器和一个客户端,但是每次尝试连接它们时,我都会立即收到连接关闭错误。 然后,我尝试对其进行编辑,但现在出现连接拒绝错误。 放弃了这一点,我决定在一个非常简单的服务器上工作,以测试Sockets和ServerSockets的基础。 这样做,我提出了以下两个类:
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
public class SimpleServer {
public static void main(String[] args) throws Exception {
System.out.println("hey there");
ServerSocket server = new ServerSocket(50010);
Socket socket = server.accept();
System.out.println("Connection at " + socket);
InputStream in = socket.getInputStream();
int c = 0;
while ((c = in.read()) != -1) {
System.out.print((char)c);
}
OutputStream out = socket.getOutputStream();
for (byte b : (new String("Thanks for connecting!")).getBytes()) {
out.write(b);
out.flush();
}
in.close();
out.close();
socket.close();
server.close();
}
}
和
import java.net.Socket;
import java.io.*;
public class SimpleClient {
public static void main(String[] args) throws Exception {
System.out.println("Attempting connection");
Socket s = new Socket("130.49.89.208", 50010);
System.out.println("Cool");
OutputStream out = s.getOutputStream();
for (byte b : (new String("Hey server\r\nThis message is from the client\r\nEnd of message\r\n")).getBytes()) {
out.write(b);
out.flush();
}
InputStream in = s.getInputStream();
int c = 0;
System.out.println("this message will print");
while ((c = in.read()) != -1) {
System.out.print((char)c);
System.out.println("this does not print");
}
out.close();
in.close();
s.close();
}
}
服务器完全可以接收到客户端的消息,但是轮到服务器写客户端时,一切都将阻塞。
服务器的输出:
-java SimpleServer
----hey there
----Connection at Socket[addr=/130.49.89.208,port=59136,localport=50010]
----Hey server
----This message is from the client
----End of message
客户的输出:
-java SimpleClient
----Attempting connection
----Cool
----this message will print
如果有帮助,客户端和服务器都可以在我的笔记本电脑上通过以太网连接到大学的Internet连接上运行。
根据Javadocs, InputStream.read()
描述为:
如果由于已到达流的末尾而没有字节可用,则返回值-1。 此方法将阻塞,直到可用输入数据,检测到流的末尾或引发异常为止。
在您的情况下,打破while循环的唯一可能性是客户端关闭连接时,从而导致流结束。
根据您的编码,这是预期的!
您的服务器代码被卡在这里,因此永远不会写回客户端
while ((c = in.read()) != -1) {
System.out.print((char)c);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.