0

我正在尝试使用套接字编程设置客户端服务器应用程序。我的客户端连接到服务器,但我无法让多个事件处理工作。我的客户端小程序有两个文本框和与每个文本框相关联的按钮。当我单击按钮一时,我试图让“Hello”显示在文本框中。当我点击按钮二时,我试图让“Hello there”显示在第二个文本框中。但是,只有一个值(我第一次单击的值)显示在两个文本框中。我的事件处理机制不正确吗?我正在实现可序列化接口,客户端服务器通信处理对象。有人可以告诉我代码中的问题是什么吗?我还没有发布 ObjectCommunication.java 代码,

非常感谢!

以下是我的服务器代码:

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



}
4

1 回答 1

0

老实说 - 我有点懒得通读你的代码并在那里寻找错误:) 不过我会在这里发布我的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);
                }
        }
}

希望这会有所帮助 :] 如果有任何不明白的地方,请随时询问更多细节 :)

于 2013-05-03T08:36:14.580 回答