在java中聊天应用程序

时间:2014-02-13 17:14:55

标签: java multithreading chat instant-messaging

我正在尝试用java创建一个聊天应用程序,但是当我无法发送到另一台机器时,我遇到了问题。 这是我的代码的一部分:

这是我的班级客户:

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;
   }

}

这是我的班级服务器:

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;
} 

我只能向自己的电脑发送消息。我怎样才能解决这个问题? 我正在我的班级里面开始创建一个GUI。

2 个答案:

答案 0 :(得分:1)

看起来你已经正确设置了服务器,但是你的客户似乎没有连接到它。您需要创建一个将连接到服务器套接字的套接字。然后,此套接字可以为您提供I / O流以发送数据。

Java's tutorial, complete with code examples

答案 1 :(得分:0)

这个问题对我来说不是那么简单...我可以向您展示Java中客户端服务器回显应用程序的基础知识...您可以在此基础上进行扩展以与我猜想的客户端之间进行聊天会话...在这里去...

import gql from 'graphql-tag' // import gql

const getBooksQuery = gql`query // describing query
  {
    books{
      name
      id
    }
  }
`;

export default {
  name: "BookList", // template name
  apollo: { // apollo instance
    query: getBooksQuery // query
  }
}

运行服务器以回应您的响应很容易...使一个或多个客户端更具挑战性...简单的jsp客户端。

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);
    }
  }
}

或更妙的是...

<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>