Search code examples
javasocketsportclient-server

client can not connect from another ip


I wrote a simple client-server application. It works very well on my computer. but when my friend tries to connect my server he can't. I create the server on my computer with port 23. Here is the part of creating the server:

public Server(int port_number) throws IOException{          
        create_Server(port_number);
    }
    
    public static void main(String[] args) throws IOException {         
        int port_number=23;         
        new Server(port_number);
    }
    
    private void create_Server(int port_number) throws IOException{         
        ss = new ServerSocket(port_number);         
        System.out.println("Server is ready!");         
        while(true){                
            s=ss.accept();                            
            System.out.println(s.getLocalAddress().getHostName() + " was connected!");
            send_con_mes();
            list.put(s,new DataOutputStream(s.getOutputStream()) );
            new ServerThread(s,this).start();
        }           
    }
}

and here is the client part ;

public void start_Chat() {

    try {

        Ip_addr = JOptionPane.showInputDialog("Enter the IP number of the server to connect : ");
        s = new Socket(Ip_addr, 23);
        
        Client_name = JOptionPane.showInputDialog("Enter your Nickname : ");
        
        dis = new DataInputStream(s.getInputStream());         
        dos = new DataOutputStream(s.getOutputStream());
        new Thread(Client.this).start();

well I can talk, send private messages etc. When I connect to server on my computer as clients, but the final problem is a client from another IP cannot get connected.


Solution

  • You have to configure your network to allow this port to be accessed. This means enabling firewall on you PC, and your routers etc. There is nothing you can do in Java to avoid having to get this right first.

    EDIT: If the other machine is trying to connect to you via an Internet router they will have to use your public IP address rather than your internal PC address. If you don't know your public address you can use a site like http://whatismyipaddress.com/. Unless you have a static IP address it can change when you reconnect. (One reason to stay connected all the time)