我正在尝试创建一个简单的客户端和服务器来发送和接收文本。客户端等待命令行输入,然后将其发送到服务器,在System.out
上显示它。但是服务器在从套接字读取时遇到困难,尽管客户端允许我输入下一行要发送。
客户端:
public class Main implements Runnable{
String [] args;
Socket socket;
PrintWriter printer;
public Main(String [] args){
this.args = args;
}
@Override
public void run() {
try {
socket = new Socket(args[0], Integer.parseInt(args[1]));
printer = new PrintWriter(socket.getOutputStream());
} catch (UnknownHostException e){
System.out.println("Unknown host.");
System.exit(2);
} catch (IOException e) {
e.printStackTrace();
}
while(true){
String textToSend = System.console().readLine();
printer.print(textToSend);
}
}
}
第printer.print(textToSend);
行不起作用。
服务器:
public class Main implements Runnable{
String [] args;
public Main(String [] args){
this.args = args;
}
@Override
public void run() {
if (args == null){
System.out.println("Argument for port missing");
System.exit(2);
}
try {
ServerSocket listener = new ServerSocket(Integer.parseInt(args[0]));
while (true){
Socket client = listener.accept();
System.out.println("Client connected");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
try{
while(true){
String text = in.readLine();
System.out.println(text);
if (in.read() == -1){
return;
}
}
}catch (IOException e){
System.out.println("Client lost");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
欢迎任何帮助。
答案 0 :(得分:2)
当你做的时候
if (in.read() == -1){
return;
}
你扔掉了一个字符
另外,在你写作时
printer.print(textToSend);
textToSend没有CR
,因此接收readLine
会阻止。
尝试将CR
添加到textToSend
的末尾或使用println
方法
答案 1 :(得分:0)
我发现错误:您必须添加换行符并调用flush:
printer.print(textToSend + "\n");
printer.flush();
这适合我。
刷新强制发送所有数据并清空所有缓冲区,以便发送数据。需要换行符,以便接收端知道该行已完成。
您检查是否未发送数据应该是line == null
,而不是read() == -1
。
这是我的整个演示代码:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while(true){
String textToSend = null;
try {
textToSend = reader.readLine();
System.out.println("read text: " + textToSend);
} catch (IOException e) {
e.printStackTrace();
}
printer.print(textToSend + "\n");
printer.flush();
System.out.println("text send");
}
服务器端的错误检查:
String text = in.readLine();
if (text == null){
return;
}
System.out.println(text);