0

我在 java eclipse 中编写了一个代码,用于使用 android TCP 连接进行服务器客户端聊天。代码运行良好,客户端是android,服务器是java。问题是当我关闭客户端并重新打开它以恢复与服务器的连接时,它不起作用。服务器无法再次找到其客户端。我只想将请求发送给客户端以重新连接并恢复服务器客户端聊天。我附上了具有三个类的 java 服务器的代码。

TCPServer.java

 public class TCPServer extends Thread {

    public static final int SERVERPORT = 1234;
    private boolean running = false;
    private PrintWriter mOut;
    private OnMessageReceived messageListener;
    private MyThread ts1,t;

    public static void main(String[] args) {

        //opens the window where the messages will be received and sent
        ServerBoard frame = new ServerBoard();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

    }

    /**
     * Constructor of the class
     * @param messageListener listens for the messages
     */
    public TCPServer(OnMessageReceived messageListener) {
        this.messageListener = messageListener;
        ts1=new MyThread();
        ts1.ts1=this;
    }


    /**
     * Method to send the messages from server to client
     * @param message the message sent by the server
     */
    public void sendMessage(String message){
        if (mOut != null && !mOut.checkError()) {
            mOut.println(message);
            mOut.flush();
        }
    }

    @Override
    public void run() {
        super.run();

        running = true;

        try {
            System.out.println("S: Connecting...");


            ServerSocket serverSocket = new ServerSocket(SERVERPORT);


            Socket client = serverSocket.accept();
            ts1.start();
            System.out.println("S: Receiving...");

            try {

                //sends the message to the client
                mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);

                //read the message received from client
                BufferedReader in = new BufferedReader(new   InputStreamReader(client.getInputStream()));


                //this while it's like a listener for messages
                while (running) {
                    String message = in.readLine();

                    if (message != null && messageListener != null) {
                        //call the method messageReceived from ServerBoard class
                        messageListener.messageReceived(message);
                    }
                }


            } catch (Exception e) {
                System.out.println("S: Error");
                e.printStackTrace();
            } finally {
                client.close();
                System.out.println("S: Done.");
            }

        } catch (Exception e) {
            System.out.println("S: Error");
            e.printStackTrace();
        }

    }



//class at on startServer button click
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }


    public void myfunc() throws Exception {
        ServerSocket serverSocket = null;
        // TODO Auto-generated method stub

         Socket client = serverSocket.accept();
         mOut = new PrintWriter(new BufferedWriter(new   OutputStreamWriter(client.getOutputStream())), true);
         BufferedReader in = new BufferedReader(new    InputStreamReader(client.getInputStream()));
        try{
         while (true) {
             String message = in.readLine();

            // if (message != null && messageListener != null) {
                 //call the method messageReceived from ServerBoard class
              //   messageListener.messageReceived(message);
             System.out.println(message);
             System.out.println("S: hellError");

             }
         }
         finally{}

     } 


    }


## ServerBoard.java ##

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;


    public class ServerBoard extends JFrame {
    private JTextArea messagesArea;
    private JButton sendButton;
    private JTextField message;
    private JButton startServer;
    private TCPServer mServer;

    public ServerBoard() {

        super("ServerBoard");

        JPanel panelFields = new JPanel();
        panelFields.setLayout(new BoxLayout(panelFields,BoxLayout.X_AXIS));

        JPanel panelFields2 = new JPanel();
        panelFields2.setLayout(new BoxLayout(panelFields2,BoxLayout.X_AXIS));

        //here we will have the text messages screen
        messagesArea = new JTextArea();
        messagesArea.setColumns(30);
        messagesArea.setRows(10);
        messagesArea.setEditable(false);

        sendButton = new JButton("Send");
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // get the message from the text view
                String messageText = message.getText();
                // add message to the message area
                messagesArea.append("\n" + messageText);
                // send the message to the client
                mServer.sendMessage(messageText);
                // clear text
                message.setText("");
            }
        });

        startServer = new JButton("Start");
        startServer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // disable the start button
                startServer.setEnabled(false);

                //creates the object OnMessageReceived asked by the TCPServer constructor
                mServer = new TCPServer(new TCPServer.OnMessageReceived() {
                    @Override


                    //TCPServer class (at while)
                    public void messageReceived(String message) {
                        messagesArea.append("\n "+message);
                    }
                });
                mServer.start();

            }
        });

        //the box where the user enters the text (EditText is called in Android)
        message = new JTextField();
        message.setSize(200, 20);

        //add the buttons and the text fields to the panel
        panelFields.add(messagesArea);
        panelFields.add(startServer);

        panelFields2.add(message);
        panelFields2.add(sendButton);

        getContentPane().add(panelFields);
        getContentPane().add(panelFields2);


        getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));

        setSize(300, 170);
        setVisible(true);
    }
    }


## MyThread.java ##


        public class MyThread extends Thread{
    public TCPServer ts1;


    public void run()
    {
        super.run();

            try {
                //if(ts1!=null)
                ts1.myfunc();

            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println("S: Error");
                e.printStackTrace();
            }
    }

    }
4

1 回答 1

2

您需要循环运行您的接受读写代码。否则,您的服务器将只接受一个客户端连接并退出。

喜欢

while (true)
{
    accept(...)

    read-and-write()
}
于 2013-09-17T05:30:13.260 回答