我有一个简单的客户端/服务器我正在努力。我必须将cookie从服务器发送到客户端(它只是一个字符串),但我的客户端不会读取inputStream。
服务器:
out = new PrintStream(sock.getOutputStream());
out.println(text);
out.println(temp2State);
out.println(temp2State);
客户端:
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String textClient = in.readLine();
String temp1= in.readLine();
String temp2= in.readLine();
这只是似乎给我带来麻烦的代码。在客户端我收到textClient但接下来的2个是空白的。如果我在发送之前在服务器上打印出temp2state,我会得到一个字符串,但是如果我在客户端打印出temp1,它就是空的。所以它似乎在翻译中丢失了。这就是说,如果使用for循环来接收数据(在类中显示),它将返回temp1但是textClient为空。这是在一个套接字上完成的,所以我确实有try / catch,但它似乎没有相关性。
备用输入读取:
for (int i = 1; i <= 5; i++) {
fromServer = in.readLine();
if (fromServer != null) {
String textClient = in.readLine();
String temp1= in.readLine();
String temp2= in.readLine();
}}
发现问题:
原来我有一个字符串试图发送附加System.lineSeperator(),发送一个空行。
答案 0 :(得分:0)
根据Java API,
public PrintStream(OutputStream out)
构造函数创建一个新的打印流,它不会自动刷新。
请尝试使用with构造函数,无论何时写入数据,都接受true为自动刷新。
请修改您的代码,如
out = new PrintStream(sock.getOutputStream(), true);