Java套接字客户端未连接到服务器

时间:2017-12-12 10:20:02

标签: java sockets client-server

当我调用搜索动物的方法时,我从服务器收到此错误。该 客户端连接到服务器但是一旦我点击了搜索方法,我就会收到以下错误:

CONNECTED. getConnection
ServerConnect, searchAnimal:  java.net.SocketException: Socket is not 
connected
CONNECTED. getConnection

getConnection是连接数据库和套接字的方法。我不知道如何解决它。求救!

这些是我的声明。我将GUI和Server放在一页代码中:

public class MGLser5 extends JFrame { //declarations
   static private JTextArea txtWin = new JTextArea();
     private JScrollPane sp = new JScrollPane(txtWin);
    private JButton clear = new JButton();
     private int port;
     Socket soc;     //client socket
     ServerSocket lstn;      //server socket 
     InputStream in;
     DataInputStream inData;
     OutputStream out;
     DataOutputStream outData;
     static String client, username, password, request;
     boolean connected;
     static String model;
     static Connection conn;
     static Statement st;
     static ResultSet rec;

private void startServer() {

        try {
            lstn = new ServerSocket(port);
            txtWin.append("Listening on port number: " + port + "\n");

            soc = lstn.accept();
            connected = true;

            in = soc.getInputStream();
            inData = new DataInputStream(in);

            out = soc.getOutputStream();
            outData = new DataOutputStream(out);
            //client = lstn.accept();
            client = inData.readUTF();


            txtWin.append("Connection established with " + client + "\n");
            while (connected) {
                model = "";
                request = inData.readUTF();
                txtWin.append("Request from client: \t" + request + "\n");
                //db/socket disconnect
                if ("Exit".equals(request)) {
                    try {
                        connected = false;
                        soc.close();
                        lstn.close();
                        in.close();
                        inData.close();
                        out.close();
                        outData.close();
                        conn.close();
                    } catch (SQLException ex) {
                        Logger.getLogger(MGLser5.class.getName()).log(Level.SEVERE, null, ex);
                    }

                } else {
                    delegate(request);

                }
            }
        } catch (IOException ex) {
            txtWin.append("Start Server 2: " + ex.getMessage() + "\n");
        }

数据库连接

public static void executeQ(String query) {
        try {
            connectDb();
            st = conn.createStatement();
            // Result set returned for a simple query
            rec = st.executeQuery(query);
        } catch (SQLException ex) {
            txtWin.append("executeQ: " + ex.getMessage() + "\n");
        }
    }

构造

public MGLser5(int portIn) {
        super("Mokgele Game Lodge ");
        port = portIn;
        add("Center", sp);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        addWindowListener(exitListener);
        setSize(400, 300);
        setVisible(true);
        startServer();
    }

搜索动物方法

try {
            String result = "";
            while (connected) {

                boolean match = Pattern.matches("[a-z]+", search);

                if (!match || !"".equalsIgnoreCase(search)) {
                    connectDb();
                    java.sql.Statement stmt = conn.createStatement();

                    String sql1 = "SELECT * FROM Animals WHERE animal_name LIKE '%" + search + "%'";
                    String sql2 = "SELECT * FROM Species WHERE species_name LIKE '%" + search + "%'";
                    String sql3 = "SELECT Animal.* FROM Species INNER JOIN Animal ON Species.species_id = Animal.species_id WHERE (Species.species_name)=\'" + search + "\';";

                    ResultSet rs = stmt.executeQuery(sql1);

                    while (rs.next()) {
                        result += "\nAnimal ID: " + rs.getString(1) + "\nAnimal Name:   " + rs.getString(2) + "\nInfo:   " + rs.getString(3) + "\nSpecies ID:    " + rs.getString(4);
                        result += "\n";
                    }

                    //If there's nothing in the Animal table, check the Species table
                    rs = stmt.executeQuery(sql2);
                    while (rs.next()) {
                        result += "\nID:    " + rs.getString(1) + "\nSpecies Name:  " + rs.getString(2);
                        result += "\n";
                    }

                    //Search for all the records of one classification, like all the felines or rodents
                    rs = stmt.executeQuery(sql3);

                    while (rs.next()) {
                        result += "\nAnimal ID: " + rs.getString(1) + "\nAnimal Name: " + rs.getString(2) + "\nInfo:    " + rs.getString(3) + "\nSpecies ID:    " + rs.getString(4);
                        result += "\n";
                    }

                    return result;
                } else /*Error mssage for wrong search input*/ {
                    JOptionPane.showMessageDialog(null, "Error.\nPlease ReEnter your search agian");
                    return "";
                }
            }
            return result;
        } catch (SQLException e) {
            System.out.println("Server, SearchAnimal:  " + e);
            connected = false;
            return "";
        }

客户端服务器

// DECLARATIONS

 private Socket clientSocket = new Socket();
    private DataInputStream Datain;
    private InputStream in;
    private DataOutputStream Dataout;
    private OutputStream out;
    static private String server = "127.0.0.1", host;//local host
    final int portIn = 8888;//port number
    boolean isConnect = true;
    public DataInputStream getInData() {
        return Datain;
    }

    public DataOutputStream getOutData() {
        return Dataout;
    }

    //CLIENT CONNECTIONS
    public void getConnection() {
        try {
            //ServerSocket svrSoc = null;
            clientSocket = new Socket(server, portIn);
            //svrSoc = new ServerSocket(portIn);
            //clientSocket = svrSoc.accept();
            //Input stream from the server
            in = clientSocket.getInputStream();
            Datain = new DataInputStream(in);

            //Output stream to the server
            out = clientSocket.getOutputStream();
            Dataout = new DataOutputStream(out);

            Dataout.writeUTF(host);

            System.out.println("CONNECTED. getConnection");
            //closeConnection();

        } catch (IOException e) {
            System.out.println("ServerConnect, getConnection1:  " + e);
            //closeConnection();
        } catch (NullPointerException e) {
            System.out.println("ServerConnect, getConnection2:  " + e);
            //closeConnection();
        }
    }

    private void getNewConnection(String request) {//send and receive data
        try {
            in = clientSocket.getInputStream();
            Datain = new DataInputStream(in);

            out = clientSocket.getOutputStream();
            Dataout = new DataOutputStream(out);
            host = request;
            Dataout.writeUTF(host);
        } catch (UnknownHostException ex) {
        } catch (IOException ex) {
        }
    }

    //Method to close the connection
    public void closeConnection() {
        try {
            clientSocket.close();
            Datain.close();
            Dataout.close();
            clientSocket.close();
            System.out.println("DISCONNECTED .");

        } catch (IOException e) {
            System.out.println("ServerConnect, closeConnection:    " + e);
        } catch (NullPointerException e) {
            System.out.println("ServerConnect, closeConnection:  " + e);
        }
    }

//服务器中搜索方法的方法

public String searchAnimal(String search) {
    String fromServer;
    try {
        in = clientSocket.getInputStream();
        Datain = new DataInputStream(in);

        out = clientSocket.getOutputStream();
        Dataout = new DataOutputStream(out);

        if (isConnect) {
            Dataout.writeUTF("searchAnimal");
            Dataout.writeUTF(search);
            fromServer = Datain.readUTF();
            //closeConnection();
            return fromServer;
        } else {
            System.out.println("ERROR SEARCH ANIMAL NOT FUNCTIONING  ");
        }
        //closeConnection();
        return "";
    } catch (IOException e) {
        System.out.println("ServerConnect, searchAnimal:  " + e);
        //closeConnection();
        return "";
    } catch (NullPointerException e) {
        System.out.println("ServerConnect, searchAnimal:  " + e);
        //closeConnection();
        return "";
    }
}

1 个答案:

答案 0 :(得分:0)

@Override
public int compare(T o1,  T o2) {
    return o2.compareTo(o1);
} 

问题出在这里。您正在创建一个没有连接的套接字,这是毫无意义的,然后永远不会连接它。