我有以下UDP客户端和servcer类,我正在尝试将一些字符串从UDPClient
发送到另一个类' UDPServer'在localhost和端口7777的同一个java项目中。我遇到的问题是我没有在UDPClient类的UDPServer类中收到任何内容。有谁知道问题出在哪里?
我感谢任何帮助!
UDPClient
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
class UDPClient {
public static void main(String args[]) throws Exception {
String aString = "Hello World";
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
sendData = aString.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 7777);
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();
}
}
UDPServer
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
class UDPServer {
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(7777);
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);
}
}
}
答案 0 :(得分:1)
您好试着检查端口分配有什么问题,因为您的代码工作正常。
启动服务器并运行以下命令:
窗
netstat -aon | FINDSTR 7777
Linux的:
netstat -aon | grep 7777
如果pid与运行UDPServer相同,您应该看到PID检查。还检查防火墙可能有问题吗?