我正在尝试在java中开发客户端/服务器通信应用程序。但是在最初阶段,我无法使用BufferedReader.readline()
从套接字的输出流中读取数据字符串。我搜索了很多,但找不到我的问题的具体答案。
调试客户端应用程序显示客户端应用程序在response.readline()
停止。
服务器:
package myserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MyServer {
public static void main(String[] args) {
String[] tokens = new String[10];
int count = 0;
ServerSocket server = null;
try {
server = new ServerSocket(16);
} catch (IOException ex) {
Logger.getLogger(OdeskServer.class.getName()).log(Level.SEVERE, null, ex);
}
if (server != null) {
while (true) {
PrintWriter response;
BufferedReader command;
String inCommand;
try {
Socket client = server.accept();
System.out.println("Connected!");
response = new PrintWriter(client.getOutputStream());
command = new BufferedReader(new InputStreamReader(client.getInputStream()));
response.print("EHLO\r\n");
command.read(); //just to stop the application to start a new iteration
} catch (IOException ex) {
Logger.getLogger(OdeskServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
客户端:
package myclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MyClient {
public static void main(String[] args) {
Socket server = null;
PrintWriter command;
BufferedReader response;
BufferedReader Console = new BufferedReader(new InputStreamReader(System.in));
try {
server = new Socket("175.107.231.218", 16);
System.out.println("Connected");
command = new PrintWriter(server.getOutputStream());
response = new BufferedReader(new InputStreamReader(server.getInputStream()));
while (server.isBound()) {
String input = response.readLine(); //Here is where the communication halts
System.out.print(input);
}
} catch (UnknownHostException ex) {
Logger.getLogger(OdeskClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(OdeskClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
关于这个问题的任何想法?
答案 0 :(得分:2)
您可能需要从服务器调用response.flush()
以确保套接字不会缓冲您的消息,等待更多写入批处理。