从MySql数据库获取从Java服务器到客户端的信息

时间:2012-03-17 09:54:14

标签: java mysql

我一直在努力让客户端和服务器发送并接收正确的信息。该程序应该能够从客户端向服务器发送查询。然后,服务器应从数据库中检索必要的信息,并作为数组发送到客户端。

Java Server:

    public class Server {
    public static void main(String[] args) throws Exception {
        ServerSocket m_ServerSocket = new ServerSocket(1211, 2, InetAddress.getLocalHost());
        int id = 0;
        while (true) {
            Socket clientSocket = m_ServerSocket.accept();
            System.out.println(clientSocket.isConnected());


            ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
            cliThread.start();
        }
     }
     }

    class ClientServiceThread extends Thread
    {
    ResultSet res = null;
    Connection conn;


    ObjectOutputStream objOut;
    PrintWriter   out;
    BufferedReader   in;

    Socket clientSocket;
    int clientID = -1;
    boolean running = true;

    ClientServiceThread(Socket s, int i)
    {
        clientSocket = s;
        clientID = i;
    }

    public void run()
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/videostore", "root", "IronFire");

        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        try 
        {
            System.out.println("Server");
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
            objOut= new ObjectOutputStream(clientSocket.getOutputStream());

            while (running)
            {
                String command = in.readLine();
                System.out.println("Query:  " + command);
                if(command.substring(0, command.indexOf(" ")).equalsIgnoreCase("SELECT+"))
                {
                    System.out.println("IN IF"); // for test
                    surname(command);
                }
                if (command.equalsIgnoreCase("quit"))
                {
                    running = false;
                    System.out.print("Stopping client thread for client : " + clientID);
                }
                else 
                {
                    out.println(command);
                    out.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void surname(String query)
    {
        try
        {
            System.out.println("In Surname"); // for test
            int count = 0; 
            int whileCounter = 0;
            Statement state = conn.createStatement();

            res = state.executeQuery(query.replace("+", ""));

            while(res.next())
            {
                count++;
            }
            String [] stringResult = new String[count];
            byte[] buff = new byte[count];
            res.beforeFirst();

            while(res.next())
            {
                stringResult[whileCounter] = res.getString(1) +"  "+  res.getString(2) +"  " + res.getString(3)  +"  "+ res.getString(5)  +"  "+ res.getString(10) +"  "+ res.getString(11) +"";
                whileCounter++;
            }

            for(int i = 0; i < stringResult.length; i++)
            {
                System.out.println(stringResult[i]);
            }

            objOut.reset();
            objOut.writeObject(stringResult);
            objOut.flush();


            System.out.println("After object");
            //objOut.close();


        }
        catch(Exception ex)
        {

        }

    }
}

Java客户端:

    public class FuncListener2 extends MainGui implements Runnable
    {
    ResultSet res = null;
    Connection conn = null;

    Socket clientSocket = null;
    PrintStream os = null;
    ObjectInputStream objIn = null;
    ObjectOutputStream objOut = null;


    public FuncListener2()
    {
        String hostName = "";

        try {
            hostName = InetAddress.getLocalHost().toString(); // to get the hostName for the exceptions
            clientSocket = new Socket(InetAddress.getLocalHost(), 1211);
            System.out.println(clientSocket.isConnected());

            os = new PrintStream(clientSocket.getOutputStream());
            objIn = new ObjectInputStream(clientSocket.getInputStream());
            listeners();

            clientSocket.setKeepAlive(true);
        } 
        catch (UnknownHostException e)
        {
            System.err.println("Don't know about host "+hostName);
            e.printStackTrace();
        }
        catch (IOException e) 
        {
            System.err.println("Couldn't get I/O for the connection to the host "+hostName);
            e.printStackTrace();
        }
        catch(Exception ex)
        {
            System.err.println(ex.getMessage());
        }
    }

    public void listeners()
    {
        System.out.println("in listener");

        butCheckOutSearchSurname.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                try
                {
                    System.out.println("surname search");
                    int count = 0;
                    Object obj = null;
                    Object [] objArray = null;
                    String [] array = null;

                    // the reason for the plus sign is to make sure the correct if statement is executed in the server
                    String query = "Select+ * FROM clientDet WHERE clientSurname = \'" + textCheckOutSearchSurname.getText() + "\'";
                    os.println(query);

                    if(objIn.readObject() != null)
                    {
                        objArray = (Object[]) objIn.readObject();
                    }
                    else
                    {
                        System.out.println("object empty");
                    }
                    objIn.reset();

                    listCheckOutClients.setListData(array);

                    System.out.println("iets");
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });
    }
    public void run()
    {       

    }
    }

这个例外是我迄今为止最大的问题。

java.io.StreamCorruptedException: invalid type code: 53
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1374)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
    at FuncListener2$1.actionPerformed(FuncListener2.java:108)

1 个答案:

答案 0 :(得分:1)

你的意思是两次打电话给readObject吗?你正在检查它是否为null,但是你不应该保存它,这样你就不会再进行第二次阅读了吗?