javaclient-serverconnectexception

simple server/client program get error : java.net.ConnectException: Connection refused


i try to write simple messenger look like it's example in book(Java How To Program 9th Edition Paul Deitel Harvey Deitel, part 27.6). after i finished , i try to test it. it work on localhost(127.0.0.1), also work on computer which connect same modem (i mean ips such 192.168.0.1 and etc) but when i want to test it on some computer cross the internet a client side code got connection refused error. i think when i client(which is my friend in somewhere in my city) try to connect server(which is me, again some where in city), when he enter my ip to connect me he connect to my modem and my modem don't send it's information to me(it's hard to explain something that u can't deeply understand it in none mother language so i'm sorry at all ) any help is important to me.

here is server code

//:D
//hello every Body:! this is my first program which use some networks !!! :-khatkeif
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.ServerSocket;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.EOFException;
public class Server extends JFrame
{
    JTextField enteredText;//input message from user
    JTextArea displayArea;//display information to user
    ObjectInputStream input;//input object from cilent
    ObjectOutputStream output;//output Object to client
    ServerSocket server;//server Socket
    Socket connection;//connecton to cilent
    public Server()//constructor
    {
        super("Server");
        setLayout(new BorderLayout(5,5));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(new JLabel("Server Messenger"),BorderLayout.NORTH);
        enteredText= new JTextField("entered message here");
        enteredText.setEditable(false);
        enteredText.addActionListener(new TextHandler());
        add(enteredText,BorderLayout.SOUTH);
        displayArea= new JTextArea();
        displayArea.setEditable(false);
        add(new JScrollPane(displayArea),BorderLayout.CENTER);
        setSize(500,500);
        setVisible(true);
    }
    public void runServer()
    {
        try
        {
            server = new ServerSocket(12345,10);//create server Socket
            while(true)
            {
                waitForConnection();//wait util a client want to connect
                openStreams();//open streams for send/get data
                processConnection();//recive message from client
            }
        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }
    }
    public void waitForConnection() throws IOException
    {
        displayMessage("waiting for client");
        connection=server.accept();//alow server for connection
        displayMessage("connect to "+connection.getInetAddress().getHostName());        
    }
    public void openStreams() throws IOException//open stream that help me to send and recive message
    {
        displayMessage("setting I/O");
        output= new ObjectOutputStream(connection.getOutputStream());//create output to send message
        output.flush();//send headers to client
        input = new ObjectInputStream(connection.getInputStream());//create input from client message
        displayMessage("Got I/O");
    }
    public void processConnection() throws IOException//recive message from client & alow server to send message to client
    {
        try
        {
            displayMessage("connected successfully");
            setTextEditable(true);//alow server to send message to client
            String reciveMessage = (String)input.readObject();//recive message form client
            while(!reciveMessage.equals("TERMINATE"))//if client send this string,make process connection finish
            {
                displayMessage(connection.getInetAddress().getHostName()+">>> "+reciveMessage);//display clinet message in display erea
                reciveMessage=(String)input.readObject();//read next message
            }
        }
        catch(ClassNotFoundException cnfe)
        {
            cnfe.printStackTrace();
        }
        displayMessage(connection.getInetAddress().getHostName()+" disconnect`");
        close();
    }
    public void close() throws IOException//close every thing
    {
        sendMessage("TERMINATE");
        input.close();
        output.close();
        connection.close();
        setTextEditable(false);
        displayMessage("connection terminated");
    }
    public void setTextEditable(final boolean val)//set text field editable
    {
        SwingUtilities.invokeLater
        (
            new Runnable()
            {
                public void run()
                {
                    enteredText.setEditable(val);
                }
            }
        );

    }
    public void displayMessage(final String message)//display message in displayArea
    {
        SwingUtilities.invokeLater(
            new Runnable()
            {
                public void run()
                {
                    displayArea.append(message+"\n");
                }
            }
        );
    }
    public void sendMessage(String message) throws IOException//send message to client
    {
        output.writeObject(message);
        output.flush();
        displayMessage("Me>>> "+message);
        enteredText.setText("");
    }
    private class TextHandler implements ActionListener//when user press enter a text in enteredText send to client
    {
        public void actionPerformed(ActionEvent ev) 
        {
            try
            {
                sendMessage(ev.getActionCommand()); 
            }
            catch(IOException ioe)
            {
                ioe.printStackTrace();
            }
        }
    }
}

and it's main

//:D
public class ServerRun
{
    public static void main(String[] args)
    {
        Server server = new Server();
        server.runServer();
    }
}

let's go for client code :D

//:D
//this is client side
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.InetAddress;
public class Client extends JFrame
{
    JTextField enteredText;//user input message
    JTextArea displayArea;//display information
    ObjectOutputStream output;//send message to server
    ObjectInputStream input;//recive message from server;
    Socket connection;//connection to server
    String serverInfo;//server name
    JButton closeB;
    JPanel downPanel;
    public Client ()
    {
        super("Client");
        setLayout(new BorderLayout(5,5));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(new JLabel("Client Messenger"),BorderLayout.NORTH);
        enteredText= new JTextField("Enter message Here");
        setTextEditable(false);
        enteredText.addActionListener(
            new ActionListener()
            {               
                public void actionPerformed(ActionEvent ev) 
                {
                    try
                    {
                        sendMessage(ev.getActionCommand());
                    }               
                    catch(IOException ioe)
                    {
                        ioe.printStackTrace();
                    }
                }
            }
        );
        closeB= new JButton("close");
        closeB.addActionListener(
            new ActionListener()
            {
                public void actionPerformed(ActionEvent ev)
                {
                    try
                    {
                        close();
                    }
                    catch(IOException ioe)
                    {
                        ioe.printStackTrace();
                    }
                }
            }
        );
        downPanel= new JPanel(new BorderLayout(5,5));
        downPanel.add(enteredText,BorderLayout.CENTER);
        downPanel.add(closeB,BorderLayout.EAST);
        add(downPanel,BorderLayout.SOUTH);
        displayArea= new JTextArea();
        displayArea.setEditable(false);
        add(new JScrollPane(displayArea),BorderLayout.CENTER);
        setSize(500,500);
        setVisible(true);
    }
    public void runClient(String host)//run client program
    {
        try
        {
            connectToServer(host);
            openStreams();
            processConnection();
        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }
    }
    public void connectToServer(String host) throws IOException//connect to server
    {
        displayMessage("connceting to " + host);
        connection = new Socket(InetAddress.getByName(host),12345);//create connection to server 
    }
    public void openStreams() throws IOException // open streams for recive/send messages
    {
        output= new ObjectOutputStream( connection.getOutputStream());//create output for send messages
        output.flush();//send headers
        input = new ObjectInputStream(connection.getInputStream());//create input for recive messages
        displayMessage("connected to "+connection.getInetAddress().getHostName());
    }
    public void processConnection()throws IOException //recive message util server trminate
    {
        try
        {
            setTextEditable(true);//alow user to send message
            String reciveMessage=(String) input.readObject();
            while(!reciveMessage.equals("TERMINATE"))
            {
                displayMessage(connection.getInetAddress().getHostName()+">>> "+reciveMessage);
                reciveMessage=(String)input.readObject();
            }
            displayMessage("connection lost");
        }
        catch(ClassNotFoundException cnfe)
        {
            displayMessage("server message is not clear");
        }
    }
    public void close() throws IOException//close every thing
    {
        sendMessage("TERMINATE");
        input.close();
        output.close();
        connection.close();
        System.exit(0);
    }
    public void sendMessage(String message) throws IOException//send message to server
    {
        output.writeObject(message);//send message to server
        output.flush();//send headers
        displayMessage("Me>>> "+message);//displate sent message to user
        enteredText.setText("");
    }
    public void displayMessage(final String message)
    {
        SwingUtilities.invokeLater(
            new Runnable()
            {
                public void run()
                {
                    displayArea.append(message+"\n");
                }
            }
        );
    }
    public void setTextEditable(final boolean val)
    {
        SwingUtilities.invokeLater(
            new Runnable()
            {
                public void run()
                {
                    enteredText.setEditable(val);
                }
            }
        );
    }
}

and it's main :

//:D
import javax.swing.JOptionPane;
public class ClientRun
{
    public static void main(String args[])
    {
        Client client = new Client();
        client.runClient(JOptionPane.showInputDialog(null,"please enter host IP:"));
    }
}

again thanks


Solution

  • Preface: This is most likely not a problem with your code, but rather a problem with your network setup. (Looks like @dimoniy beat me to answering, hopefully this sends the same idea as his).

    The most likely reason that your friend cannot connect to your server is because he cannot get through your modem. In order for someone to connect to your server (from the code the port looks to be 12345) you need to change some settings in your router/modem (Which you can usually connect to by going to 192.168.1.1 or 192.168.0.1) and adding a "Port forwarding rule". This will allow connections "outside" of your network (aka the rest of the world) to connect to the server on that port.

    You will need to add a 'Port Forwarding' rule to your modem/router that redirects all the traffic on port 12345 to the local ip of where you are hosting the server (your computers ip; found by ipconfig or ifconfig cmd in console/terminal). Then you will need to get your 'External IP' which can be found by Googling "what's my ip". This is the "address" of your network to the rest of the world. This is the IP that you need to give to your friend.

    Your friend needs to use your External IP that you gave him, along with the port that the server is running on, and your router should forward his connection to your server and should work!

    Some topics you might want research some more are: "external IP vs internal IP" and "Port Forwarding".

    Hope this helps!