Chat between two different computers

Asked

Viewed 730 times

0

I’m new to this socket thing and I’m having trouble connecting two computers that are on the same network. When I run the client and the server on the same machine, it works... but when I do it on different machines, the server does not identify the client connection.

I have read many questions and answers in various forums, watched videos on youtube, tried different solutions, already put the server IP in client code and nothing...

Would anyone know what I’m doing wrong? Thank you!

Server

import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.UIManager;

public class Server extends JFrame implements ActionListener,Runnable  {
ServerSocket ss;
Socket s;
BufferedReader br;
BufferedWriter bw;
List list;
JButton btnExit;
JTextArea text;
JButton btnSend;

public Server() {
    setTitle("Secret Chat - Server");
    setSize(741,495);
    setLocation(300,0);
    getContentPane().setLayout(null);

    list = new List();
    list.setBounds(10, 48, 692, 275);
    getContentPane().add(list);

    btnExit = new JButton("Exit");
    btnExit.setBounds(613, 11, 89, 23);
    getContentPane().add(btnExit);
    btnExit.addActionListener(this);

    text = new JTextArea();
    text.setForeground(UIManager.getColor("ToggleButton.focus"));
    text.setLineWrap(true);
    text.setBounds(10, 338, 692, 74);
    getContentPane().add(text);

    btnSend = new JButton("Send");
    btnSend.setBounds(613, 423, 89, 23);
    getContentPane().add(btnSend);
    btnSend.addActionListener(this);

    setVisible(true);

    try
    {           
        list.add("Aguardando conexão de cliente...\n");

        ss = new ServerSocket(8375);

        s = ss.accept();
        br = new BufferedReader(new InputStreamReader(
                s.getInputStream()));
        bw = new BufferedWriter(new OutputStreamWriter(
                s.getOutputStream()));
        bw.write("... Você está conectado! ...");
        bw.newLine();
        bw.flush();
        Thread th;
        th = new Thread(this);
        th.start();
    }
    catch(Exception e)
    {
        //System.out.println("Exceção: " + e);
    }
}

 public static void main(String[] args) throws Exception
  {

     new Server();         

  }

@Override
public void run() {
    try
    {
        s.setSoTimeout(1);
    } catch(Exception e)
    {
        System.out.println("Exceção: " + e);
    }
    while (true)
    {
        try
        {
            list.add(br.readLine());
        }
        catch (Exception ex)
        {
            //System.out.println("Exceção: " + ex);
        }
    }

}

@Override
public void actionPerformed(ActionEvent e) {
     if (e.getSource().equals(btnExit))
         System.exit(0);
     else{try{
         list.add("Eu (Servidor): " + text.getText());
         bw.write("Patty " + text.getText());
         bw.newLine();
         bw.flush();
         text.setText("");
         } catch(Exception m){}
     }


}                    

}

Client

import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

    public class Client extends JFrame implements ActionListener,Runnable 
{
    List list;
    JTextArea text;
    JButton btnExit;
    JButton btnSend;
    Socket s;
    BufferedReader br;
    BufferedWriter bw;

    public Client() {
        setTitle("Secret Chat - Client");
        getContentPane().setLayout(null);

        list = new List();
        list.setBounds(10, 47, 692, 275);
        getContentPane().add(list);

        text = new JTextArea();
        text.setLineWrap(true);
        text.setBounds(10, 338, 692, 74);
        getContentPane().add(text);

        btnExit = new JButton("Exit");
        btnExit.setBounds(613, 11, 89, 23);
        btnExit.addActionListener(this);
        getContentPane().add(btnExit);

        btnSend = new JButton("Send");
        btnSend.setBounds(613, 423, 89, 23);
        btnSend.addActionListener(this);
        getContentPane().add(btnSend);

        setSize(741,495);
        setLocation(300,0);

        setVisible(true);

        try{
            /*Put the current IP address for current machine  
            if you didn't have an actual server and clients
            if you have an actual server and clients put the client IP address*/
            s = new Socket("10.1.XX.XXX",8375); // é aqui onde coloco o IP do servidor
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            bw.write("... Um usuário anônimo se conectou! ...");
            bw.newLine();
            bw.flush();
            Thread th;
            th = new Thread(this);
            th.start();

        } catch(Exception e){
            System.out.println(e);
        }
    }


    public static void main(String[] args) throws Exception
    {
        new Client();

    }

    @Override
    public void run() {
        try
        {
            s.setSoTimeout(2500);
        } catch(Exception e)
        {
            //System.out.println("Exceção: " + e);
        }

        while (true)
        {
            try
            {
                list.add(br.readLine());
            }
            catch (Exception e)
            {
                //System.out.println("Exceção: " + e);
            }
        }

    }

    @Override
    public void actionPerformed(ActionEvent e) {
         if (e.getSource().equals(btnExit))
             System.exit(0);
         else {
             try
             {
                 list.add("Eu (Cliente): " + text.getText());
                 bw.write("Anônimo: " + text.getText());
                 bw.newLine();
                 bw.flush();
                 text.setText("");
             } catch(Exception ex)
             {
                 //System.out.println("Exceção: " + ex);
             }
         }

    }                    
}                  
  • I tested localhost and it worked perfectly. Unfortunately there is no way I can test on different machines, but you probably need to pass the server ip in the client, and see if there are no firewall blocks too.

  • The site actually works.. = / the problem is when I try with different computers (which is what I need).. The address I should put is the Ipv4 that I get through the ipconfig command in cmd, right? Thank you so much for the warning! I’ll do it. w ^

  • This depends, if you are on local network, is the address provided by your router. You also need to check the firewall. Windows usually block incoming connections.

  • All right! I’ll check the firewall.

  • Try to uncomment the Catchs too, they exist precisely to point out problems in the application, if you leave empty, will never know the origin of problems that cause exceptions. I decoded your catchs here and several error messages appeared.

  • Yes.. I decrypted =/ So.. I already checked the firewall (I even added a new rule), but... still not working

  • To no longer show those exceptions, I changed the setSoTimeOut to a very high value...

  • It is the firewall that is blocking even, but I could not make the chat pick up without disabling it, even adding an input rule to the port being used in the program.

Show 4 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.