有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java SocketException:两个客户端并行运行时连接重置

我尝试将两个客户端连接到服务器,但出现异常:“java.net.SocketException:Connection reset”。如何并行连接两个客户端

服务器代码:

package Server;

import Server.IServerStrategy;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
private int port;
private int listeningIntervalMS;
private IServerStrategy strategy;
private volatile boolean stop;
private ExecutorService threadPool; // Thread pool
private Configurations configuration;


public Server(int port, int listeningIntervalMS, IServerStrategy strategy) {
    this.port = port;
    this.listeningIntervalMS = listeningIntervalMS;
    this.strategy = strategy;
    configuration=Configurations.getInstance();

    // initialize a new fixed thread pool with 2 threads:
    Properties prop = new Properties();
    try (InputStream input =new FileInputStream(("C:/Users/liron/IdeaProjects/ATP-Project-PartB/resources/config.properties"))) {
        prop.load(input);
        this.threadPool = Executors.newFixedThreadPool(Integer.parseInt(prop.getProperty("threadPoolSize")));
    }catch (IOException ex) {
        ex.printStackTrace();
    }
}

public void start(){
    new Thread(()->{
        runServer();
    }).start();
}


public void runServer(){
    try {
        ServerSocket serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(listeningIntervalMS);

        while (!stop) {
            try {
                Socket clientSocket = serverSocket.accept();

                // Insert the new task into the thread pool:
                threadPool.submit(() -> {
                    handleClient(clientSocket);
                });

            } catch (SocketTimeoutException e){
            }
        }
        serverSocket.close();
        threadPool.shutdownNow(); // do not allow any new tasks into the thread pool, and also interrupts all running threads (do not terminate the threads, so if they do not handle interrupts properly, they could never stop...)
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void handleClient(Socket clientSocket) {
    try {
        strategy.applyStrategy(clientSocket.getInputStream(), clientSocket.getOutputStream());
        clientSocket.close();
    } catch (IOException e){
        e.printStackTrace();
    }
}

public void stop(){
    stop = true;
}

}

客户端代码:

package Client;
import Client.IClientStrategy;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class Client {
private InetAddress serverIP;
private int serverPort;
private IClientStrategy strategy;

public Client(InetAddress serverIP, int serverPort, IClientStrategy strategy) {
    this.serverIP = serverIP;
    this.serverPort = serverPort;
    this.strategy = strategy;
}

public void communicateWithServer(){
    try(Socket serverSocket = new Socket(serverIP, serverPort)){
        System.out.println("connected to server - IP = " + serverIP + ", Port = " + serverPort);
        strategy.clientStrategy(serverSocket.getInputStream(), serverSocket.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

启动客户机和服务器的主服务器(我不能将其分为两个类):

import Server.*;
import algorithms.mazeGenerators.*;
import algorithms.search.*;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RunCommunicateWithServers {
    public static void main(String[] args) throws Exception {
//Initializing servers
Server mazeGeneratingServer = new Server(5400, 1000, new ServerStrategyGenerateMaze());
//Starting servers
mazeGeneratingServer.start();

new Thread(()->{
        CommunicateWithServer_MazeGenerating();
    }).start();
    new Thread(()->{
        CommunicateWithServer_MazeGenerating();
    }).start();

//Stopping all servers
    mazeGeneratingServer.stop();
}



rivate static void CommunicateWithServer_MazeGenerating() {
    try {
        Client client = new Client(InetAddress.getLocalHost(), 5400, new IClientStrategy() {
                    @Override
                    public void clientStrategy(InputStream inFromServer, OutputStream outToServer) {
                        try {
                            ObjectOutputStream toServer = new ObjectOutputStream(outToServer);
                            ObjectInputStream fromServer = new ObjectInputStream(inFromServer);
                            toServer.flush();
                            int[] mazeDimensions = new int[]{20, 20};
                            toServer.writeObject(mazeDimensions); //send maze
                            toServer.flush();
                            byte[] compressedMaze = (byte[]) fromServer.readObject(); //read generated maze (compressed with MyCompressor) from server
                            InputStream is = new MyDecompressorInputStream(new ByteArrayInputStream(compressedMaze));
                            byte[] decompressedMaze = new byte[424 /*CHANGE SIZE ACCORDING TO YOU MAZE SIZE*/]; //allocating byte[] for the decompressed maze -
                            is.read(decompressedMaze); //Fill decompressedMaze
                            Maze maze = new Maze(decompressedMaze);
                            maze.print();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
        client.communicateWithServer();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}

我得到的例外是:

java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.io.ObjectInputStream$PeekInputStream.read(ObjectInputStream.java:2663)
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2679)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:3156)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:862)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:358)
at algorithms.test.RunCommunicateWithServers$1.clientStrategy(RunCommunicateWithServers.java:56)
at Client.Client.communicateWithServer(Client.java:23)
at algorithms.test.RunCommunicateWithServers.CommunicateWithServer_MazeGenerating(RunCommunicateWithServers.java:72)
at algorithms.test.RunCommunicateWithServers.lambda$main$0(RunCommunicateWithServers.java:35)
at java.lang.Thread.run(Thread.java:748)

代码中的第56行引用:ObjectOutputStream-toServer=新ObjectOutputStream(outToServer)

谢谢你的帮助


共 (0) 个答案