0

I wrote a code in java eclipse for server client chat using android TCP connection. The code runs well, client is android and server is java. The problem is that when i close the client, and reopen it to resume the connection with the server, it does not work. The server is not able to find its client again. I just want to send the request to the client for the reconnection and resume the server client chat. I'm attaching the code for java server having three classes.

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

    }

1 Answer 1

2

You need to run your accept-read-write code in a loop. Otherwise your server will only accept one client connection and exit.

Like

while (true)
{
    accept(...)

    read-and-write()
}
Sign up to request clarification or add additional context in comments.

2 Comments

yes I already tried this, but then i get error java.lang.NullPointerException at TCPServer.myfunc(TCPServer.java:119) at MyThread.run(MyThread.java:12)
Kindly read my code thoroughly and then show me your modifications. I'm continuously modifying it for 2 weeks but i did not get the desired results. your effort will be highly appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.