我正在使用Netbeans IDE尝试在客户端和服务器之间建立UDP连接,这是一个简单的程序, UDPClient 将字符串发送到 UDPServer ,服务器将字符串大写并将其发送回客户端。端和服务器端在一个分开的项目中。
我的客户端UDPClient
的类代码:
package udpclient;
import java.io.*;
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws IOException{
//get input from user
BufferedReader user_in = new BufferedReader(
new InputStreamReader(System.in));
//create udp socket connection
DatagramSocket socket = new DatagramSocket();
//creat buffers to process data
byte[] inData = new byte[1024];
byte[] outData = new byte[1024];
//get ip destination wanted
InetAddress IP = InetAddress.getByName("localhost");
//read data from user
System.out.println("Enter Data to send to server: ");
outData = user_in.readLine().getBytes();
/*
* make pkts for interaction
*/
//send pkts
DatagramPacket sendPkt = new DatagramPacket(outData, outData.length, IP, 9876);
socket.send(sendPkt);
//receive pkts
DatagramPacket recievePkt = new DatagramPacket(inData, inData.length);
socket.receive(recievePkt);
System.out.println("Replay from Server: "+recievePkt.getData());
}
}
和我的服务器端类
UDPServer
: package udpserver;
import java.io.*;
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws IOException{
// TODO code application logic
//connection
DatagramSocket socket = new DatagramSocket();
//pkt buffers
byte[] inServer = new byte[1024];
byte[] outServer = new byte[1024];
//receive pkt
DatagramPacket rcvPkt = new DatagramPacket(inServer,inServer.length);
socket.receive(rcvPkt);
//display receive
System.out.println("Packet Received!");
//retrive pkt info to send response to same sender
InetAddress IP = rcvPkt.getAddress();
int port = rcvPkt.getPort();
//process data
String temp = new String(rcvPkt.getData());
temp = temp.toUpperCase();
outServer = temp.getBytes();
//send response packet to sender
DatagramPacket sndPkt = new DatagramPacket(outServer, outServer.length, IP, port);
socket.send(sndPkt);
}
}
计算程序正常运行并且不输出错误。服务器根本没有收到数据包,也没有与客户端进行交互。为什么会这样呢?
最佳答案
您尚未在服务器中指定任何侦听端口,因此服务器在随机可用端口上侦听。
在服务器端尝试
DatagramSocket socket = new DatagramSocket(9876);