Aplicação de conversação em java

Estou a tentar fazer uma aplicação de chat em java, mas tive um problema quando não consegui enviar para outra máquina. Aqui está parte dos meus códigos: Este é o meu cliente de turma.
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;
   }

}

Este é o meu servidor de classe:

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;
} 
Só posso enviar uma mensagem para o meu computador. Como posso resolver isto? Estou a começar a minha linha dentro da minha turma que faz um GUI.

Author: marcelo, 2014-02-13

2 answers

Parece que configuraste bem o teu servidor, mas o teu cliente não parece ligar-se a ele. Você precisa criar um socket que irá se conectar ao socket do servidor. Este socket pode então dar-lhe fluxos de E/S para enviar dados através.

Tutorial do Java, Completo com exemplos de código

 1
Author: John M, 2014-02-13 17:22:37
A questão não é assim tão simples para mim...Posso mostrar-lhe o básico para a aplicação cliente echo em java...Você pode expandir sobre isso para fazer uma sessão de chat entre clientes, eu suponho...aqui vai...
public class MultiThreadServer implements Runnable {

Socket csocket;
private static boolean quitFlag = false;

MultiThreadServer(Socket csocket) {
    this.csocket = csocket;
}

public static void main(String args[]) throws Exception {
    ServerSocket ssock = new ServerSocket(1234);
    System.out.println("Listening");

    while (!quitFlag) {
        Socket sock = ssock.accept();
        System.out.println("Connected");
        new Thread(new MultiThreadServer(sock)).start();
     }
}

public void run() {
    try {

        BufferedReader in = new BufferedReader(new InputStreamReader(csocket.getInputStream()));

        String action = in.readLine();

        PrintStream pstream = new PrintStream(csocket.getOutputStream());
        System.out.printf("Server received... " + action + " ...action\n");
        switch (action) {
            case "bottle":
                for (int i = 3; i >= 0; i--) {
                    pstream.println("<p>" + i + " bottles of beer on the wall" + "</p>");
                }
                pstream.println("<p>" + action + "</p>");

                break;
            case "echo":
                pstream.println("<p>" + action + "</p>");
                break;
            case "quit":
                quitFlag = true;
                break;
        }
        pstream.close();
        csocket.close();
    } catch (IOException e) {
        System.out.println(e);
    }
  }
}
Executar o servidor para ecoar a sua resposta é fácil...tornar o cliente ou clientes são mais desafiadores...um simples cliente jsp..
<BODY>
    <H1>Creating Client/Server Applications</H1>


    <% 
    String serverInput = request.getParameter("serverInput");
    //String serverInput = "bottle";   


    try{
        int character;
        Socket socket = new Socket("127.0.0.1", 1234);

        InputStream inSocket = socket.getInputStream();
        OutputStream outSocket = socket.getOutputStream();

        String str = serverInput+"\n";
        byte buffer[] = str.getBytes();
        outSocket.write(buffer);

        while ((character = inSocket.read()) != -1) {
            out.print((char) character);
        }

        socket.close();

    }
    catch(java.net.ConnectException e){
    %>
        You must first start the server application 
        at the command prompt.
    <%
    }
    %>
</BODY>
Ou melhor ainda...
     <body>
        <%String name = request.getParameter("inputString");%>
        <h1>Creating Client Applications</h1>

        <p>Client Sent... <%=name%> ...to Server</p>

    <% 
    //String serverInput = "bottle";   


    try{
        int character;
        Socket socket = new Socket("127.0.0.1", 1234);


        OutputStream outSocket = socket.getOutputStream();

        String str = name;
        byte buffer[] = str.getBytes();
        outSocket.write(buffer);


        socket.close();

    }
    catch(java.net.ConnectException e){
    %>
        You must first start the server application 
        at the command prompt.
    <%
    }
    %>




    </body>
 0
Author: Ralph Weber, 2018-09-09 13:33:57