我试图找出为什么我可以从服务器向客户端发送消息但是当我尝试相反的方式(从客户端向服务器发送消息)时,程序暂停,就像它正在等待某些操作到发生。
还有如何防止套接字立即关闭。
这是代码:
客户等级
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
Client aClient = new Client();
aClient.run();
}
private Socket socket;
private PrintWriter toServer;
private BufferedReader fromServer;
public void run() {
try {
socket = new Socket("localhost", 9000);
if (socket.isConnected()){
System.out.println("CONNECTED");
}
fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toServer = new PrintWriter(socket.getOutputStream());
toServer.print("hello server");
System.out.print(fromServer.readLine());
toServer.close();
socket.close();
} catch (Exception error) {
System.out.println("CLIENT ERROR: " + error);
}
}
}
服务器类
import java.io.*;
import java.net*;
public class Server {
public static void main(String[] args) {
Server aServer = new Server();
aServer.run();
}
private ServerSocket mainSocket;
private Socket socket;
private PrintWriter toClient;
private BufferedReader fromClient;
public Server(){
try{
mainSocket = new ServerSocket(9000);
}
catch (Exception error){
System.out.print("Error :"+error);
}
}
public void run() {
System.out.println("WAITING FOR CLIENTS");
try {
socket = mainSocket.accept();
if(socket.isConnected()) {
System.out.println("CONNECTED.");
}
fromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toClient = new PrintWriter(socket.getOutputStream());
System.out.println(fromClient.readLine());
toClient.print("hello Client");
toClient.close();
}
catch (Exception error) {
System.out.println("SERVER ERROR :" + error);
}
}
}
答案 0 :(得分:1)
在toServer.print("hello server");
到Client
课程之前添加此内容。它从System.in
读取并发送到Server
类:
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromUser;
while((fromUser = stdIn.readLine()) != null) {
System.out.println("Client: " + fromUser);
toServer.println(fromUser);
}
并Server
类在System.out.println(fromClient.readLine());
之前将其读取行添加到客户端并打印到System.out
:
String inputLineFromClient;
while ((inputLineFromClient = fromClient.readLine()) != null) {
System.out.println(inputLine);
}
在调用方法close()或发生某些Exception
之前,套接字未关闭。
答案 1 :(得分:0)
您的服务器没有阅读任何内容。 使用 fromClient.readLine();