簡體   English   中英

Java客戶端服務器-客戶端的多個事件處理

[英]Java Client Server - Multiple Event Handling for the Client

我正在嘗試使用套接字編程來設置客戶端服務器應用程序。 我的客戶端連接到服務器,但是我無法使多個事件處理正常工作。 我的客戶端小程序有兩個文本框和與每個文本框相關的按鈕。 當我單擊一個按鈕時,我試圖在文本框中顯示“ Hello”。 當我單擊兩個按鈕時,我試圖在第二個文本框中顯示“ Hello there”。 但是,兩個文本框中都只顯示一個值(我第一次單擊的值)。 我的事件處理機制不正確嗎? 我正在實現可序列化的接口,並且客戶端服務器通信處理對象。 有人可以告訴我代碼中的問題是什么嗎? 我尚未發布ObjectCommunication.java代碼,但它僅實現了可序列化的接口,並具有getter和setter(將字符串作為輸入參數)方法。

非常感謝!

以下是我的服務器代碼:

import java.io.*;
import java.net.*;

public class Server_App {
    public static void main(String[] args) {

        try {
            ServerSocket holder = new ServerSocket(4500);

            for (;;) {
                Socket incoming = holder.accept();
                new ServerThread(incoming).start();

            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

class ServerThread extends Thread

{

    public ServerThread(Socket i) {
        incoming = i;
    }

    public void run() {
        try {


            ObjectCommunication hold = new ObjectCommunication();

            ObjectInputStream input = new ObjectInputStream(incoming.getInputStream());

            ObjectOutputStream output = new ObjectOutputStream(incoming.getOutputStream());


            hold = (ObjectCommunication) input.readObject();

            if ((hold.getMessage()).equals("Event 1")) {

                System.out.println("Message read: " + hold.getMessage());

                hold.setMessage("Hello!");

            } else if ((hold.getMessage()).equals("Event 2")) {
                System.out.println("Message read:" + hold.getMessage());

                hold.setMessage("Hello there!");
            }

            output.writeObject(hold);

            input.close();

            output.close();

            incoming.close();

        } catch (Exception e) {
            System.out.println(e);
        }
    }

    ObjectCommunication hold = null;
    private Socket incoming;

}

以下是客戶端代碼:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class Client_App extends Applet {
    TextField textVal;
    TextField anotherTextVal;
    Socket socket;
    ObjectCommunication hold = new ObjectCommunication();
    ObjectCommunication temp = new ObjectCommunication();
    ObjectOutputStream OutputStream;
    ObjectInputStream InputStream;

    public void init() {

        socketConnection();

        createGUI();

        validate();
    }

    public void socketConnection() {

        try {
            socket = new Socket("127.0.0.1", 4500);
        } catch (Exception e) {
            System.out.println("Unknown Host");
        }

        try {

            OutputStream = new ObjectOutputStream(socket.getOutputStream());
            InputStream = new ObjectInputStream(socket.getInputStream());

        } catch (IOException ex) {
            System.out.println("Error: " + ex);
            return;
        }


    }

    public void createGUI() {

        Button button = new Button("Hello Button");

        add(button);


        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                button_actionPerformed(evt);

            }
        });


        textVal = new TextField(6);
        add(textVal);

        Button anotherButton = new Button("Hello there Button");

        add(anotherButton);

        anotherButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                anotherButton_actionPerformed(evt);
            }

        });


        anotherTextVal = new TextField(6);
        add(anotherTextVal);


    }

    public void button_actionPerformed(ActionEvent e) {



        String actionCommand = e.getActionCommand();

        if (e.getSource() instanceof Button)
            if (actionCommand.equals("Hello Button")) {


                try {

                    temp.setMessage("Event 1");

                    //OutputStream.writeObject(temp); 

                    new SendToServer().start();

                    new ListenToServer().start();


                } catch (Exception ex) {
                    System.out.println("Communication didn't work!");
                }

                textVal.setText(hold.getMessage());
            }
    }

    public void anotherButton_actionPerformed(ActionEvent evt) {
        String action_Command = evt.getActionCommand();

        if (evt.getSource() instanceof Button)
            if (action_Command.equals("Hello there Button")) {


                try {

                    temp.setMessage("Event 2");

                    new SendToServer().start();

                    new ListenToServer().start();

                } catch (Exception ex) {
                    System.out.println("Communication didn't work!");
                }

                anotherTextVal.setText(hold.getMessage());
            }


    }

    class ListenToServer extends Thread {
        public void run() {
            while (true) {
                try {
                    hold = (ObjectCommunication) InputStream.readObject();
                } catch (IOException e) {} catch (ClassNotFoundException e2) {}
            }
        }
    }

    class SendToServer extends Thread {

        public void run() {
            while (true) {
                try {
                    OutputStream.writeObject(temp);
                } catch (IOException e) {}
            }
        }
    }



}

老實說-我有點懶於閱讀您的代碼並在其中尋找錯誤:)盡管如此,我還是在這里向您發布了socket-based multiple client-server應用程序的代碼段。

import java.net.*;
import java.io.*;

class ServeConnection extends Thread {
        private Socket socket = null;
        private BufferedReader in = null;
        private PrintWriter out = null;

        public ServeConnection(Socket s) throws IOException {

                // init connection with client
                socket = s;
                try {
                        in = new BufferedReader(new InputStreamReader(
                                        this.socket.getInputStream()));
                        out = new PrintWriter(this.socket.getOutputStream(), true);
                } catch (IOException e) {
                        System.err.println("Couldn't get I/O.");
                        System.exit(1);
                }                
                start();
        }

        public void run() {

                System.out.println("client accepted from: " + socket.getInetAddress()
                                + ":" + socket.getPort());

           // get commands from client, until is he communicating or until no error
           // occurs
                String inputLine, outputLine;

                try {
                        while ((inputLine = in.readLine()) != null) {


                                System.out.println("request: " + inputLine);
                                outputLine = inputLine;    
                                out.println("I've recived "+outputLine);                                 
                } catch (IOException e) {
                        e.printStackTrace();
                }

                System.out.println("server ending");
                out.close();
                try {
                        in.close();
                        socket.close();
                } catch (IOException e) {
                        e.printStackTrace();
                }
        }
}

class Server {
        public static void svr_main(int port) throws IOException {
                ServerSocket serverSocket = null;
                try {
                        serverSocket = new ServerSocket(port);
                } catch (IOException e) {
                        System.err.println("Could not listen on port: " + port);
                        System.exit(1);
                }

                System.out.println("Server ready");

                try {
                        while (true) {
                                Socket socket = serverSocket.accept();
                                try {
                                        new ServeConnection(socket);
                                } catch (IOException e) {
                                        System.err.println("IO Exception");
                                }
                        }
                } finally {
                        serverSocket.close();
                }
        }
}

class Client {      
        static Socket echoSocket = null;
        static PrintWriter out = null;
        static BufferedReader in = null;





        public static void cli_main(int port, String servername) throws
IOException {
                try {
                        echoSocket = new Socket(servername, port);
                        out = new PrintWriter(echoSocket.getOutputStream(), true);
                        in = new BufferedReader(new InputStreamReader(
                                        echoSocket.getInputStream()));
                } catch (UnknownHostException e) {
                        System.err.println("Don't know about host: " + servername);
                        System.exit(1);
                } catch (IOException e) {
                        System.err.println("Couldn't get I/O for " + servername);
                        System.exit(1);
                }

                System.out.println("Client ready!");
                while (true) {

                        inputLine = (in.readLine().toString());
                        if (inputLine == null) {
                                System.out.println("Client closing!");
                                break;
                        }

                        // get the input and tokenize it
                        String[] tokens = inputLine.split(" ");


                }

                out.close();
                in.close();
                echoSocket.close();
                System.out.println("Client closing");
        }
}

public class MyClientServerSnippet{
        public static void main(String[] args) throws IOException {
                if (args.length == 0) {
                        System.err.println("Client: java snippet.MyClientServerSnippet<hostname> <port>");
                        System.err.println("Server: java snippet.MyClientServerSnippet<port>");
                         System.exit(1);
                }
                else if (args.length > 1) {                   
                        System.out.println("Starting client...\n");
                        Client client = new Client();
                        client.cli_main(3049, "127.0.0.1");
                } else {
                        System.out.println("Starting server...\n");
                        Server server = new Server();
                        server.svr_main(3049);
                }
        }
}

希望對您有所幫助:]如果有什么不容易理解的地方,請隨時詢問更多詳細信息:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM