我想了解UDP无连接客户端 - 服务器对。我在Book Computer Networking:Top Top Down方法中得到了一些代码。 该计划如下: - 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。 我很想知道如何修复Client的端口,就像我们在给定的java程序中为Server做的那样,以便可以在特定端口上将消息返回给Client。
例如,如果 客户端将向服务器发送UDP消息,服务器将在端口号9876上启动并运行,并将原始消息返回到端口9877上的客户端。请帮助。
答案 0 :(得分:1)
您不需要客户端的固定端口,只需要客户端需要固定的IP地址。您自己的代码应该已经正常工作。但是还有其他问题:
String sentence = new String( receivePacket.getData());
错误。它应该是String sentence = 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
进行接收和发送,只需更改数据。