简体   繁体   中英

Java Client Server - Multiple Event Handling for the Client

I'm trying to setup a client server application using socket programming. My client connects to the server, but I'm unable to get the multiple event handling to work. My client applet has two text boxes and buttons associated with each one of of them. When I click button one, I was trying to get "Hello" to be displayed in the text box. When I click on button two, I was trying to get "Hello there" to be displayed in the second text box. However, only one value (the value I first click) shows up in both of the text boxes. Is my event handling mechanism incorrect? I am implementing the serializable interface and the client server communication deals with objects. Can someone please tell me what the problem in the code is? I haven't posted the ObjectCommunication.java code, but it simply implements the serializable interface and has the getter and setter (takes a string as an input parameter) method.

Many thanks!

The following is my server code:

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;

}

The following is the client code:

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) {}
            }
        }
    }



}

To be honest - I'm a little bit lazy to read through your code and seek there for a bug :) Nevertheless I'll post you here my snippet for socket-based multiple client-server application..

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);
                }
        }
}

Hope this helps :] If anything would be ununderstandable, don't hesitate to ask for more details :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM