我是服务器和客户端类的代码。我有两个类,ServerApp作为服务器,ClientApp作为本地计算机的客户端。
我首先运行ServerApp类,然后运行ClientApp类。在运行ClientApp类之后,我在eclipse控制台中编写了一些消息" Hello Server"然后在显示客户端消息的ServerApp控制台中打印消息。
但是,当我运行ServerApp类并在控制台中编写一些文本并运行ClientApp时,控制台中不会显示任何消息。
我无法理解如何在eclipse控制台中显示双向消息通信?请建议我如何在eclipse中执行双向通信(客户端服务器)。
服务器应用
import java.io.*;
import java.net.*;
public class ServerApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
ServerSocket Server_Socket;
Server_Socket = new ServerSocket(5555);
Socket clientSocket = null;
clientSocket = Server_Socket.accept();
DataInputStream input;
input = new DataInputStream(clientSocket.getInputStream());
System.out.println(input.readUTF());
DataOutputStream output;
output = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "", str2 = "";
while (!str.equals("stop"))
{
str = input.readUTF();
System.out.println("client says: " + str);
str2 = br.readLine();
output.writeUTF(str2);
output.flush();
}
input.close();
clientSocket.close();
Server_Socket.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
客户端应用
import java.io.*;
import java.net.*;
public class ClientApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Socket Client_Socket;
Client_Socket = new Socket("localhost", 5555);
DataInputStream input;
input = new DataInputStream(Client_Socket.getInputStream());
DataOutputStream output;
output = new DataOutputStream(Client_Socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "", str2 = "";
while (!str.equals("stop")) {
str = br.readLine();
output.writeUTF(str);
output.flush();
str2 = input.readUTF();
System.out.println("Server says: " + str2);
}
output.flush();
output.close();
Client_Socket.close();
} catch (Exception e) {
System.out.println(e);
}
}
}