我想写代码让客户端发送一个字符串到服务器,服务器打印字符串并回复一个字符串,然后客户端打印字符串服务器回复。
我的服务器Java Socket为什么服务器不能回复客户端
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = null;
Socket s = null;
try {
ss = new ServerSocket(34000);
s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream());
while (true) {
String string = in.readLine();
if (string != null) {
System.out.println("br: " + string);
if (string.equals("end")) {
out.write("to end");
out.flush();
out.close();
System.out.println("end");
// break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
s.close();
ss.close();
}
}
}
我的客户:
public class Client {
public static void main(String[] args) {
Socket socket =null;
try {
socket = new Socket("localhost", 34000);
BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
String string = "";
string = "end";
out.write(string);
out.flush();
while(true){
String string2 = in.readLine();
if(string2.equals("to end")){
System.out.println("yes sir");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
System.out.println("closed client");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
是有一些出头错了吗?如果我在客户端类中删除了“while(true)...”的代码,那没问题。
所以你能解释一下发生了什么 –
你发送newLine吗? – Fildor
“public String readLine() 读取一行文本。行被认为由换行符('\ n'),回车符('\ r')或后跟回车符立即通过换行。“ - > http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine() – Fildor