предположим, что мы используем следующие классы для иллюстрации клиента и сервера:
Клиент
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client {
private PrintWriter toServer;
private BufferedReader fromServer;
private Socket socket;
public Client() throws IOException {
socket = new Socket("127.0.0.1", 3000);
}
public void openStreams() throws IOException {
toServer = new PrintWriter(socket.getOutputStream(), true);
fromServer = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
}
public void closeStreams() throws IOException {
fromServer.close();
toServer.close();
socket.close();
}
public void run() throws IOException {
openStreams();
String msg = "";
Scanner scanner = new Scanner(System.in);
toServer.println("Hello from Client.");
while (!"exit".equals(msg)) {
System.out.println(">");
toServer.println("msg");
String tmp = fromServer.readLine();
System.out.println("Server said: " + tmp);
}
closeStreams();
}
}
Сервер
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class myServer {
private static ServerSocket serverSocket;
private static Socket socket;
private static PrintWriter toClient;
private static BufferedReader fromClient;
public static void run() throws IOException {
System.out.println("Server is waiting for connections...");
while (true) {
openStreams();
processClient();
closeStreams();
}
}
public static void openStreams() throws IOException {
serverSocket = new ServerSocket(3000);
socket = serverSocket.accept();
toClient = new PrintWriter(socket.getOutputStream(), true);
fromClient = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
}
public static void closeStreams() throws IOException {
fromClient.close();
toClient.close();
socket.close();
serverSocket.close();
}
public static void processClient() throws IOException {
System.out.println("Connection established.");
String msg = fromClient.readLine();
toClient.println("Client said " + msg);
}
}
если мы сначала запустим сервери тогда, когда сервер будет готов, мы запустим клиент, мы получим следующую ошибку:
Error in Client Software caused connection abort: recv failed
в чем проблема?