java 如何让两个客户互相聊天?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2087185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 19:22:18  来源:igfitidea点击:

how can make two clients chat with each other?

javanetworking

提问by Johanna

this is not my homework(my homework is just about doing chat with a client and server which it works correctly especially with your help[:-)] but I want to make two clients chat with each other,I don't know that when i get text from the first one how can I send that text to the other client.would you please help me.thanks.

这不是我的作业(我的作业只是与客户端和服务器聊天,它可以正常工作,尤其是在您的帮助下[:-)] 但我想让两个客户端互相聊天,我不知道什么时候我从第一个收到文本,如何将该文本发送给另一个客户。请您帮帮我。谢谢。

public class MainServer {

static Socket client = null;
static ServerSocket server = null;



public static void main(String[] args) {
    System.out.println("Server is starting...");
    System.out.println("Server is listening...");

    try {
        server = new ServerSocket(5050);
    } catch (IOException ex) {
        System.out.println("Could not listen on port 5050");
        System.exit(-1);

    }
    try {
        boolean done = false;
        while (!done) {

            client = server.accept();
            System.out.println("Client Connected...");
            BufferedReader streamIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintWriter streamOut = new PrintWriter(client.getOutputStream(),true);
            String line = streamIn.readLine();
            if (line.equalsIgnoreCase("bye")) {
                streamIn.close();
                client.close();
                server.close();
                done = true;
            } else {
                System.out.println(line);
                streamOut.println(line);
            }
        }

    } catch (IOException e) {
        System.out.println("IO Error in streams " + e);
    }
}}

回答by Pico

That's it, your two "clients" will both act as client and server : Listening to incoming things on a socket and sending things over an other sockets.

就是这样,您的两个“客户端”将同时充当客户端和服务器:侦听套接字上的传入内容并通过其他套接字发送内容。

回答by trashgod

Here is a very simple, ~100 line, GUI chat program.

这是一个非常简单的约 100 行 GUI聊天程序

回答by Kaleb Brasee

On the server, you can keep a Set of all the clients that are currently connected to the server. The server should listen for messages (can do this with a ServerSocket, and clients connect with normal Sockets). Each time the server receives a message, it sends this message back to all clients in the Set, and the clients display the message.

在服务器上,您可以保留当前连接到服务器的所有客户端的集合。服务器应该侦听消息(可以使用ServerSocket执行此操作,并且客户端使用普通Sockets连接)。服务器每次收到消息时,都会将此消息发送回 Set 中的所有客户端,客户端显示该消息。

EDIT:this is for a client-server system, where clients connect to a central server instead of directly to each other. If you want to do direct client-to-client, one of them will just have to act as the server, and you'll need to implement a chat UI in both.

编辑:这适用于客户端 - 服务器系统,其中客户端连接到中央服务器而不是直接相互连接。如果您想直接进行客户端到客户端,则其中一个只需要充当服务器,并且您需要在两者中实现聊天 UI。

回答by Eric Petroelje

Unless you want to get into really complicated P2P discovery protocols, you would have to have a server to act at least as an intermediary.

除非您想进入非常复杂的 P2P 发现协议,否则您至少需要一台服务器来充当中介。

In order to establish a direct client to client connection, the clients would need to know each others IP addresses. To do this, each client would first connect and "register" itself with a central server.

为了建立直接的客户端到客户端连接,客户端需要知道彼此的 IP 地址。为此,每个客户端将首先连接到中央服务器并向其“注册”。

When a client wants to talk to another client, it would ask for that client's address from the server, then establish a connection directly with that client. So each client is acting both as a client (establishing connections with the server and other clients) and as a server (accepting connections from other clients).

当一个客户端想和另一个客户端通话时,它会从服务器请求那个客户端的地址,然后直接与那个客户端建立连接。因此,每个客户端既充当客户端(与服务器和其他客户端建立连接)又充当服务器(接受来自其他客户端的连接)。

It seems simple in theory, but in practice it gets more complicated. For example, what if the client you want to connect to is behind a firewall? You could have a hole in the firewall for incoming connections to get through, or you could fall back to having the communication go through the server, or if one of the clients is behind a firewall and the other isn't, the server could mediate the connection in the opposite direction.

这在理论上看起来很简单,但在实践中变得更加复杂。例如,如果您要连接的客户端位于防火墙后面怎么办?您可能在防火墙上有一个漏洞以供传入连接通过,或者您可以退回让通信通过服务器,或者如果其中一个客户端在防火墙后面而另一个不在,则服务器可以进行调解反方向的连接。

回答by Andreas Dolk

Basically, there are two approaches:

基本上,有两种方法:

  1. One Chat server that receives all messages and distributes/forwards them to the clients (xmpp/jabber works this way)
  2. One server that connects clients directly. Like on peer-to-peer networks
  1. 一个接收所有消息并将它们分发/转发到客户端的聊天服务器(xmpp/jabber 以这种方式工作)
  2. 一台直接连接客户端的服务器。就像在点对点网络上一样

Looking back at your previous work, I think, the first approach is more feasible.

回顾你之前的工作,我认为,第一种方法更可行。

The server will offer one port where new clients can connect. After a client requests to participate/use the server, there server spawns a worker thread with a server socket on a different (available) port number and tell the client that port number. This is the reserved communication channel for that client with the server.

服务器将提供一个新客户端可以连接的端口。在客户端请求参与/使用服务器后,服务器会在不同的(可用)端口号上生成一个带有服务器套接字的工作线程,并告诉客户端该端口号。这是该客户端与服务器的保留通信通道。

The rest is pretty straightforward: a client can send a new chat message, the server will pick it up and send it to all connected clients.

剩下的很简单:客户端可以发送一条新的聊天消息,服务器会接收它并将其发送给所有连接的客户端。

If a client disconnects, the worker thread will close the socket, return it to the pool and terminate.

如果客户端断开连接,工作线程将关闭套接字,将其返回到池中并终止。

回答by Peter Lang

Have a look at Building an Internet chat system.

看看建立一个互联网聊天系统

This explains how to write simple Clients and a Server with Java.

这解释了如何使用 Java 编写简单的客户端和服务器。