我正在尝试用Java创建一个非常简单的Socket
/ ServerSocket
程序。下面列出了我的两个类,它们都在同一台机器上运行。问题是,连接似乎建立得很好,但是当我尝试将套接字从客户端写入服务器时,似乎没有任何事情发生。服务器永远不会从in.readLine()
返回,程序停止运行。我无法弄清楚为什么会这样。
以下是我的课程:
TheServer.java:
public class TheServer {
public static void main(String[] args) {
BufferedReader in = null;
PrintWriter out = null;
try {
ServerSocket serv = new ServerSocket(2255);
Socket sock = serv.accept();
in = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
out = new PrintWriter(sock.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Connection established by Server");
try {
String line;
while ((line = in.readLine()) != "Bye") {
System.out.println(line + "Received");
out.println(line.toUpperCase());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
TheClient.java:
public class theClient {
public static void main(String[] args) {
BufferedReader in = null;
PrintWriter out = null;
try {
Socket sock = new Socket("localhost", 2255);
in = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
out = new PrintWriter(sock.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Connection established by Client");
try {
while (true) {
BufferedReader read = new BufferedReader(new InputStreamReader(
System.in));
String line = read.readLine();
out.println(line.trim());
System.out.println(in.readLine().trim());
if (line == "Bye")
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:3)
对于PrintWriter对象,在每次写入尝试后,
obj.flush();