处理连接服务器-多客户端会出现以下错误:对等连接重置:SocketException

早安大家, 对于uni项目,我必须创建一个多线程服务器-客户端系统。 在客户端和服务器之间的连接过程中出现了一些问题:当服务器运行并执行客户端时,连接正在工作。  -无论如何,当客户端注销时,服务器崩溃一次又一次地重复相同的错误。 我使用ClientHandler处理多线程连接,并且在第60行显示了错误。 这里有三个类:

服务器类

public class Server {

private static final int SPORT = 5056;
private static ArrayList<Thread> ThreadAttivi = new ArrayList<Thread>() {
};
private static ArrayList<Impiegato> ImpiegatiLoggati = new ArrayList<Impiegato>() {
};
private Socket s;

public Server() {
    Inetaddress ip;
    try {
        ip = Inetaddress.getByName("localhost");
        this.s = null;
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void runServer() throws IOException,InterruptedException

{

    // inizializzazione dei dipendenti
    Funzionario f = new Funzionario("mario","super","funzionario","Ferrari","Via cavallotti",3,"2012-03-01","ciao");
    Impiegato f2 = new Funzionario("gino","gini","Fiat","Via lattea",33,"hi");
    Impiegato f3 = new Funzionario("paolo","bitta","Lancia","Via davanti",1,"bye");
    Impiegato f4 = new Funzionario("tea","tea","Audi","Via Mascagni",2,"salut");

    // server is listening on port 5056
    ServerSocket serverSocket = new ServerSocket(SPORT);

    System.out.println("In ascolto sulla porta:" + SPORT);

    // running infinite loop for getting
    // client request
    long beginning = System.currentTimeMillis();
    long end = beginning + 30000;

    while (true) // dopo un tot di tempo smettiamo di ascoltare e partono le funzioni randomiche
    {

        s = null;

        try {

            s = serverSocket.accept();

            {
                // socket object to receive incoming client requests

                System.out.println("A new client is connected : " + s);

                // obtaining input and out streams
                DataInputStream dis = new DataInputStream(s.getInputStream());
                DataOutputStream dos = new DataOutputStream(s.getOutputStream());

                System.out.println("Assigning new thread for this client");

                // create a new thread object
                Thread t = new ClientHandler(dis,dos,s);

                // Invoking the start() method
                t.start();
                ThreadAttivi.add(t);

            }

        } catch (IOException e) {
            s.close();
            e.printStackTrace();
        }

    }
}

public static void main(String[] args) {
    try {
        new Server().runServer();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
} }

客户端类:

public class Client {
private static final int SPORT = 5056;
private PrintWriter output;
private BufferedReader read;
private Socket s;
private ObjectInputStream in;
private ObjectOutputStream os;
private Inetaddress ip;

public Client() {

    try {
        this.ip = Inetaddress.getByName("localhost");
        this.s = new Socket(ip,SPORT);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public void run() throws UnknownHostException,IOException {

    try {
        Scanner scn = new Scanner(System.in);

        //this.in = new ObjectInputStream(s.getInputStream());
        this.os = new ObjectOutputStream(s.getOutputStream());
        this.os.flush();

        // getting localhost ip

        // establish the connection with server port 5056

        // obtaining input and out streams
        DataInputStream dis = new DataInputStream(s.getInputStream());
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());

        // the following loop performs the exchange of
        // information between client and client handler
        while (true) {

            // l'user scrive username e password al ClientHandler
            System.out.println(dis.readUTF()); // leggiamo dal ClientHandler
            String username = scn.nextLine(); // scriviamo da console username
            dos.writeUTF(username); // inviamo il dato al ClientHandler

            System.out.println(dis.readUTF());
            String password = scn.nextLine();
            dos.writeUTF(password);
            // l'user riceve una risposta

            String received = dis.readUTF();

            if (received.equals("Dati sbagliati")) {
                System.out.println("Closing this connection : " + s);
                System.out.println("Dati sbagliati");
                scn.close();
                dis.close();
                dos.close();
                s.close();
                break;
            }
            else if (received.equals("Already logged")) {
                System.out.println("Closing this connection : " + s);
                System.out.println("Utente già connesso");
                scn.close();
                dis.close();
                dos.close();
                s.close();
                break;
            }
            else if (received.equals("loggato")) {
                System.out.println("Sei connesso!!!\nCosa vuoi fare?");
                //Object userLogged = (Impiegato)in.readObject();
                //if (userLogged instanceof Funzionario) {
                //  Funzionario funz = (Funzionario) userLogged;
                //  Funzionario.funzioneRandom(funz);
                    break;
                }
            else System.out.println("no opzioni");

            // printing date or time as requested by client

            // System.out.println(received);
        }

        // closing resources
        scn.close();
        dis.close();
        dos.close();
        in.close();
        os.close();
        s.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) throws IOException {

    Client client = new Client();
    client.run();

}}

ClientHandler类:

public class ClientHandler extends Thread {

private static ArrayList<ClientHandler> ListaClientHandler = new ArrayList<ClientHandler>() {};
private static ArrayList<Impiegato> ImpiegatiLoggati = new ArrayList<Impiegato>() {};
private boolean already_registered = false;
private boolean dati_sbagliati = false;
private boolean impiegato_loggato = false;
final DataInputStream dis;
final DataOutputStream dos;
private Socket client;
private int bytesRead;
private Connect c = new Connect();
private BufferedReader input;
private PrintWriter output;
private static final long SLEEPTIME = 2000;
private Impiegato curr_impiegato;

private Funzionario curr_funzionario;

// caricamento dei dati nel ClientHandler
private static ArrayList<Impiegato> Impiegati = Impiegato.getListaImpiegati();

// Constructor
public ClientHandler(DataInputStream dis,DataOutputStream dos,Socket client) {
    this.dis = dis;
    this.dos = dos;
    this.client = client;
    ListaClientHandler.add(this);
}

public static ArrayList<ClientHandler> getListaCH() {
    return ListaClientHandler;
}

public static void setListaImpiegati(ArrayList<ClientHandler> listaCH) {
    ListaClientHandler = listaCH;
}

// QUESTO E' IL NOSTRO
// SISTEMA-------------------------------------------------------------------------------------------------------------

@Override
public void run() {
    String username;
    String password;
    String toreturn;

    while (true) {
        try {

            dos.writeUTF("username:\n"); // Ask user the username
            username = dis.readUTF(); // receive the answer from client

            dos.writeUTF("password:\n"); // Ask user the password
            password = dis.readUTF(); // receive the answer from client

            // invio differenti messaggi a seconda del risultato del login

            if (checkLog(username,password)) // se si è loggato
            {

                impiegato_loggato = true;
                System.out.println("Client " + this.client + " è loggato...");
                dos.writeUTF("loggato");
                while (ListaClientHandler.size() != ImpiegatiLoggati.size()) {
                    // System.out.println("Waiting");
                }
                dos.writeUTF("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz");
                this.dopoaccesso();
                break;
            } else if (dati_sbagliati) // comunico che ci sono errori nell'inserimento dei dati
            {
                dos.writeUTF("Dati sbagliati");
                ListaClientHandler.remove(this);
                client.close();
                break;
            }

            else if (already_registered) {
                dos.writeUTF("Already logged");
                client.close();
                break;
            }

        }

        catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

这是错误消息:

java.net.SocketException: Connection reset by peer: socket write error
at java.base/java.net.SocketOutputStream.socketWrite0(Native Method)
at java.base/java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:110)
at java.base/java.net.SocketOutputStream.write(SocketOutputStream.java:150)
at java.base/java.io.DataOutputStream.write(DataOutputStream.java:107)
at java.base/java.io.DataOutputStream.writeUTF(DataOutputStream.java:401)
at java.base/java.io.DataOutputStream.writeUTF(DataOutputStream.java:323)
at progettoAzienda.ClientHandler.run(ClientHandler.java:60)
litao7777 回答:处理连接服务器-多客户端会出现以下错误:对等连接重置:SocketException

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2998755.html

大家都在问