简体   繁体   English

如何使客户端服务器Java应用程序在一个端口上发送消息,而在另一个端口上接收消息?

[英]How do I make a client-server Java application to send messages on one port but receive them on another?

I am currently trying to make an application that will send messages to a server using one port, but will receive messages on another port. 我当前正在尝试制作一个应用程序,该应用程序将使用一个端口将消息发送到服务器,但是将在另一个端口上接收消息。 However, based on tutorials I have followed, it looks like the act of connecting to the server is where ports come into play and my client is receiving and sending messages on the same port. 但是,根据我遵循的教程,似乎连接到服务器的行为是发挥作用的端口,而我的客户端正在同一端口上接收和发送消息。 How do I make it so it sends on one port but receives on the other? 如何使它在一个端口上发送但在另一个端口上接收呢?

Here is the code that I think is relevant from the client side (I put some stuff that seems unrelated because I think they are things that would be altered by receiving on one port but sending on another, and ignore the comment about replacing inetaddress, that is just me working on implementing this in a gui): 这是我认为与客户端相关的代码(我放入了一些看起来无关的东西,因为我认为它们是可以通过在一个端口上接收而在另一个端口上发送而改变的东西,而忽略了有关替换inetaddress的评论,只是我正在努力在gui中实现此功能):

public void startRunning(){
    try{
        connectToServer();
        setupStreams();
        whileChatting();

    }catch(EOFException eofException){
        showMessage("\n Client terminated connection");

    }catch(IOException ioException){
        ioException.printStackTrace();
    }finally{
        closeStuff();
    }

}



//connect to server
private void connectToServer() throws IOException{
    showMessage("Attempting connection... \n");
    connection = new Socket(InetAddress.getByName(serverIP), 480);//replace serverIP with ipTextField.getText or set serverIP to equal ipTextField.getText? Same with port number.
    showMessage("Connected to:  " + connection.getInetAddress().getHostName() );
}


//set up streams to send and receive messages
private void setupStreams() throws IOException{
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();
    input = new ObjectInputStream(connection.getInputStream());
    showMessage("\n Streams are good!  \n");
}


//while talking with server
private void whileChatting() throws IOException{
    ableToType(true);
    do{
        try{
            message = (String) input.readObject();
            showMessage("\n" + message);
        }catch(ClassNotFoundException classNotfoundException){
            showMessage("\n Don't know that object type");
        }

    }while(!message.equals("SERVER - END"));
}

//send messages to server
private void sendMessage(String message){
    try{
        output.writeObject("CLIENT - " + message);
        output.flush();
        showMessage("\nCLIENT - " + message);
    }catch(IOException ioException){
        messageWindow.append("\n something messed up ");
    }

}


//change/update message window
private void showMessage(final String m){
    SwingUtilities.invokeLater(
        new Runnable(){
            public void run(){
                messageWindow.append(m);
            }
        }
    );

}

EDIT/UPDATE: To help clarify some things, here is some more information. 编辑/更新:为了帮助弄清楚一些事情,这里有一些更多信息。 The device that sends the first message is connected to a sensor, and it sends information when that sensor detects something to the other device. 发送第一条消息的设备已连接到传感器,并且当该传感器检测到某些东西时,它会向另一设备发送信息。 The receiving device sends a message back on a different port telling the original sending device how to respond. 接收设备在另一个端口上发送一条消息,告诉原始发送设备如何响应。 Lets name these two devices the "reporter-action taker" and the "decision maker-commander". 让我们将这两个设备命名为“举报人”和“决策者-指挥官”。

If you want to use TCP/IP sockets you can't use aa socket to send and another to read. 如果要使用TCP / IP套接字,则不能使用aa套接字发送和使用另一个套接字读取。 That's not what they are for. 那不是他们的目的。

If you use a centralized distributed algorithm (server/client communication) you have to set the server to listen on a single socket port with the ServerSocket class: then the server tries to accept clients through that socket. 如果使用集中式分布式算法(服务器/客户端通信),则必须将服务器设置为使用ServerSocket类在单个套接字端口上进行侦听:然后服务器尝试通过该套接字接受客户端。

Example: 例:

ServerSocket listener = new ServerSocket(Port)
While (true) {
    new Clienthandler(listener.accept());
}

The server will listen on that port, and when a client tries to connect to that port if it is accepted the server launches its handler. 服务器将侦听该端口,并且当客户端尝试连接到该端口(如果被接受)时,服务器将启动其处理程序。 On this handler constructor the Socket object used on the client is received on an argument and can then be used to get the writers and the readers. 在此处理程序构造函数上,在客户端上使用的Socket对象在参数上接收,然后可以用于获取作者和读者。 The reader on this handler class will be the writer on the client class and vice-versa, maybe that's what you were looking for. 该处理程序类的读者将是客户端类的作者,反之亦然,也许正是您所要的。

Your question about using two ports in this manner is a bit strange. 您关于以这种方式使用两个端口的问题有点奇怪。 You state that you have a client and a server and that they should communicate on different ports. 您声明您有一个客户端和一个服务器,并且它们应该在不同的端口上进行通信。

Just to clarify picture the server as a hanging rack for jackets with several hooks in a row. 只是为了阐明图片,该服务器是一排挂有多个挂钩的夹克的挂架。 Each port the server listened on represents a hook. 服务器监听的每个端口都代表一个钩子。 When it comes to the client server relationship the client or jacket knows where to find its hook, however the hook is blind and have no idea where to find jackets. 当涉及到客户端服务器关系时,客户端或夹克知道在哪里可以找到它的钩子,但是该钩子是盲目的并且不知道在哪里可以找到夹克。

Now, the client selects a port or a hook and connects to it. 现在,客户端选择一个端口或一个挂钩并连接到它。 The connection is like a pipeline with two pipes. 连接就像一个带有两个管道的管道。 One for the client to deliver data to the server with and the other to send data from the server back to the client. 一个供客户端与之一起将数据传送到服务器,另一个供客户端将数据从服务器发送回客户端。 When the connection is established data can be transferred both ways. 建立连接后,可以双向传输数据。 This means that we only need one port open on the server to send data both from the client to the server and in the opposite direction. 这意味着我们只需要在服务器上打开一个端口即可将数据从客户端发送到服务器,并且方向相反。

The reason for only having one open port open on the server for the clients to connect to is that holding an open port for connections is hard to do on a regular client computer. 服务器上只有一个开放端口供客户端连接的原因是,在常规客户端计算机上很难保持开放端口进行连接。 The normal desktop user will be behind several firewalls blocking incoming connections. 普通的台式机用户将位于几个阻止传入连接的防火墙之后。 If that wasn't the case the client would probably be hacked senseless from malicious viruses. 如果不是这种情况,客户端可能会遭到恶意病毒的毫无意义的黑客攻击。

Moving on with the two port solution we could not call this a client server connection per say. 继续讲两个端口的解决方案,我们不能说这是一个客户端服务器连接。 It would be more like a peer to peer connection or something like that. 它更像是对等连接或类似的东西。 But if this is what you want to do, the application connecting first would have to start by telling the other application what ip and port to use for connecting back, it should probably also want to give some kind of token that are to be used to pair the new incoming connection when connecting back. 但是,如果这是您要执行的操作,则首先要连接的应用程序必须先告诉其他应用程序要使用的IP和端口来进行连接,它可能还应该提供某种令牌,以用于进行连接。重新连接时配对新的传入连接。

You should take note that making such an implementation is not a good idea most of the time as it complicates things a whole lot for simple data transfer between a client and server application. 您应该注意,在大多数情况下,实现这样的实现不是一个好主意,因为它会使客户端和服务器应用程序之间的简单数据传输变得非常复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 客户端服务器应用程序-如何将查询发送到数据库并接收结果? - Client-server application - how to send queries to database and receive results? 如何使我的Java Swing应用程序成为客户端 - 服务器应用程序? - How to make my Java Swing application a Client-Server application? 如何进行循环以从服务器(在客户端-服务器应用程序中)读取/下载文件? - How do I make a loop to read/download file from server (in client-server application)? 客户端 - 服务器应用程序JAVA,服务器不接收数据 - Client-Server application JAVA, server don't receive data 如何在Java客户端服务器程序中将消息发送到多个客户端 - How do i send the message to multiple clients in java Client-Server Program 如何以正确的顺序输出自动的Client-Server Java网络代码? - How do I make my automated Client-Server Java networking code output in the correct sequence? 客户端-服务器应用程序 Java - Client-Server application Java Java 中的客户端 - 服务器应用程序 - Client-server application in Java 如何在java客户端 - 服务器模型中设计消息 - how to design messages in a java client-server model Java桌面应用程序客户端-服务器合而为一 - Java Desktop Application Client-Server all in one
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM