gpt4 book ai didi

java - 如何在java中的UDP无连接客户端-服务器对的固定端口上运行客户端程序

转载 作者:行者123 更新时间:2023-12-01 10:06:43 26 4
gpt4 key购买 nike

我正在尝试了解 UDP 无连接客户端-服务器对。我在《计算机网络:自上而下的方法》一书中获得了一些代码。计划如下:- UDPServer.java:

    import java.io.*;
import java.net.*;

class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}

UDPClient.java

import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}

在给定的代码中,我们修复了服务器的端口号,即 9876。我很好奇如何修复客户端的端口,就像我们在给定的 java 程序中为服务器所做的那样,以便可以在特定端口上将消息返回给客户端。

例如,如果客户端将向服务器发送一条UDP消息,服务器将在端口号9876上启动并运行,并在端口9877上将原始消息返回给客户端。请帮忙。

最佳答案

客户端不需要固定端口,就像客户端不需要固定 IP 地址一样。您自己的代码应该已经可以正常工作。但还有其他问题:

String sentence = new String( receivePacket.getData());

错了。它应该是String Sent = new String( receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());

      System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);

此代码会将回复发送回请求来源处。一种更简单的方法是使用相同的 DatagramPacket 进行接收和发送,只需更改数据即可。

关于java - 如何在java中的UDP无连接客户端-服务器对的固定端口上运行客户端程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36397601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com