我将创建一个简单的服务器来处理一些 UDP 数据报。我的代码如下:
public class UDPServer implements Runnable{
private static final Logger logger = Logger.getLogger("UDPServer");
private DatagramSocket datagramSocket = null;
private int port;
public UDPServer(int portNumber) {
this.port = portNumber;
try {
this.datagramSocket = new DatagramSocket(port, InetAddress.getLocalHost());
} catch (UnknownHostException ex) {
logger.info("Server creating failed 1...");
} catch (SocketException e) {
logger.info("Server creating failed 2...");
}
logger.info("Server created...");
logger.log(Level.INFO, "Datagram socket: INETAddress: {0} Port: {1}", new Object[]{datagramSocket.getInetAddress(), datagramSocket.getPort()});
}
private void runServer() {
logger.info("Starting the server...");
try {
while (true) {
byte[] buffer = new byte[64];
DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
logger.log(Level.INFO, "Waiting for an incoming packet on {0}", this.datagramSocket.getInetAddress());
datagramSocket.receive(receivedPacket);
logger.log(Level.INFO, "Received packet from: {0}", receivedPacket.getSocketAddress());
new DatagramConsumer(receivedPacket).start();
}
} catch (SocketException ex) {
// logging...
} catch (IOException ex) {
// logging
}
}
@Override
public void run() {
this.runServer();
}
}
它只是创建了一个服务器,并提供了一种检索和处理数据报的方法......我不明白的是,当我创建服务器对象时:
UDPServer server = null;
try {
server = new UDPServer(12395);
Thread serverThread = new Thread(server);
serverThread.start();
serverThread.join();
}
我看到这样的输出:
INFO: Server created...
INFO: Datagram socket: INETAddress: null Port: -1
INFO: Starting the server...
INFO: Waiting for an incoming packet on null
我是网络新手,我不知道我做错了什么......我期待我的服务器应该在定义的端口和本地地址上监听传入的数据报......