javamultithreadingchatinstant-messaging

Chat Application in java


I'm trying to make a chat application in java, but I had a problem, when I couldn't send to another machine. Here's part of my codes:

This is my class client:

public class EnvioSocket {
    public static boolean enviarSocket(String nome, String ip, int porta,
        String mensagem) {
        String dados = nome + " : " + mensagem;
        try {
            Socket socket = new Socket(ip, porta);
            OutputStream outToServer = socket.getOutputStream();
            DataOutputStream out = new DataOutputStream(outToServer);
            out.writeUTF(dados);
            out.close();
            socket.close();

        } catch (UnknownHostException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
            return false;
        } catch (IOException e) {
           JOptionPane.showMessageDialog(null, e.getMessage());
           return false;
        }
        return true;
   }

}

This is my class server:

public class ServidorThread implements Runnable {
    private JTextArea menssage;

    public ServidorThread(JTextArea menssage) {
        this.menssage = menssage;
    }
    @Override
    public void run() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(Porta.PORTA);
            while (true) {
                Socket acceptedSocket = serverSocket.accept();
                DataInputStream in = new DataInputStream(
                    acceptedSocket.getInputStream());
                String menssage = in.readUTF();
                this.menssage.append(DateUtils.dateToString(new Date(), "dd/MM/yyyy HH:mm") + " " + menssage + "\n");
                in.close();
                acceptedSocket.close();
            }
        } catch (IOException e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }
}



define a port to socket
public final class Porta {
    private Porta() {
    }

    public static final int PORTA = 6066;
} 

I can only send a message to my own computer. How can I fix this? I'm starting my thread inside of my class that make a GUI.


Solution

  • It looks like you've set up your Server right, but your client doesn't seem to ever connect to it. You need to create a socket which will connect to the server socket. This socket can then give you I/O streams to send data through.

    Java's tutorial, complete with code examples