简体   繁体   中英

JAVA Chat app not working over internet

I created a chat app in Java it worked when i open server and clients on different terminals but same computer. Today i gave it to my friend to test it over internet and its not working(Connection timed out ,yes i am using muiltithreads). I have allowed port (i am using 4242) in my firewall and my friends. But still not working.

I have read couple of similar question asked on internet but each has different steps (none working) and also i am not getting all steps though.

Some said that router is hiding my ip address so i need to enable port forwarding (i dont know how) . Also there must be a way without it. Many software works like this but doesnt need us to enable port forwarding. Will using a mobile hotspot instead of modem work(I am so DUMB!).

i am noob in this area, studied networking in JAVA yesterday and made app yesterday night. Help me run my app over internet in simple language. Will be gratefull if it works without port forwarding and static ip address. Let me know if you need to see my code.

Server Side:

   import java.io.*;
import java.net.*;
import java.util.*;

class DailyAdviceS
{
    ArrayList<PrintWriter> Clients=new ArrayList<PrintWriter>();
    Socket sock;
    public static void main(String args[])
    {
        DailyAdviceS ad= new DailyAdviceS();
        ad.go();
    }
    private void go()
    {
        try
        {
            ServerSocket server= new ServerSocket(4242);
            InetAddress ip;
            ip = InetAddress.getLocalHost();
            System.out.println("Current IP address : " + ip.getHostAddress());
            while(true)
            {
                sock=server.accept();
                PrintWriter writer = new PrintWriter(sock.getOutputStream());
                Clients.add(writer);
                Thread foundR= new Thread(new nodeR(sock));
                foundR.start();
                System.out.println("got a connection");
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    private void SendAll(String Chat,String name)
    {
        Iterator it=Clients.iterator();
        while(it.hasNext())
        {
            try
            {
                PrintWriter writer= (PrintWriter)it.next();
                writer.println(name+" /t "+Chat);
                writer.flush();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    class nodeR implements Runnable                     //recieve message from clients
    {
        private String hostName; 
        private BufferedReader reader;
        public nodeR(Socket s)
        {
            try
            {
                String hostName = s.getInetAddress().getHostName();
                System.out.println(hostName);
                InputStreamReader in= new InputStreamReader(s.getInputStream());
                reader = new BufferedReader(in);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        public void run()
        {
            String Message;
            try
            {
                String Name=InetAddress.getLocalHost().getCanonicalHostName();  
                SendAll(Name+" Ready","");
                while(true)
                {
                    while ((Message=reader.readLine())!=null) 
                    {
                        SendAll(Message,Name);
                    }
                }

            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}

CLient Side:

import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.text.*;

class DailyAdvice
{
    private JTextArea ar= new JTextArea(100,100);
    private JTextField field = new JTextField(17);
    private JButton button;
    private Socket chat;
    private InputStreamReader stream;
    private BufferedReader reader;
    private PrintWriter writer;

    public static void main(String args[])
    {
        DailyAdvice ad= new DailyAdvice();
        ad.setnw();
        ad.go();

        }
    private void go()
    {
        JFrame frame= new JFrame("Chat with RedHead");
        JPanel panel= new JPanel();
        ar.setLineWrap(true);
        ar.setWrapStyleWord(true);
        ar.setEditable(false);
        JScrollPane scroll= new JScrollPane(ar);
        scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
        panel.add(field);

        DefaultCaret caret = (DefaultCaret) ar.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

        button= new JButton("Send");
        panel.add(button);
        frame.getRootPane().setDefaultButton(button);
        frame.add(scroll,BorderLayout.CENTER);
        frame.add(panel,BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
        frame.setBounds(50,50,300,300);
        frame.setVisible(true);
        Runnable r= new Recieve();
        Thread send= new Thread(new Send());
        Thread recieve= new Thread(r);
        send.start();
        recieve.start();

    }
    private void setnw()
    {
        try
        {
            chat = new Socket("122.176.8.153",4242);
            stream= new InputStreamReader(chat.getInputStream());
            reader= new BufferedReader(stream);
            writer = new PrintWriter(chat.getOutputStream());
            System.out.println("connection established");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
    class Send implements Runnable
    {
        public void run()
        {
            button.addActionListener(new timetosend());

        }
        class timetosend implements ActionListener
        {
            public void actionPerformed(ActionEvent ev)
            {
                try
                {
                    String msg =field.getText();
                    writer.println(msg);
                    writer.flush();
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }
                field.setText("");
            }
        }
    }
    class Recieve implements Runnable
    {
        public void run()
        {
            try
            {
                String input;
                while ((input= reader.readLine())!=null)
                {
                    String[] result=input.split("/t");
                    ar.append(result[0]+" : "+result[1]+'\n');
                }
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }
}

Please make sure your application is not using the private IP to connect to your server if accessing over the internet. you can check your PC's public IP from the site below which is currently allocated to your PC, and can use this in your client apps.
And also make sure you have configure the port in port forwarding in your switch/router and if it is not allowed by your ISP, you can use any port forwarding software on your PC to do that.

http://www.get-myip.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM