我有下一个代码,基于使用 Java UDPSocket() 的示例(不是内置类):
package BomberButti;
import java.io.*;
import java.net.*;
/**
* BomberServer
* Hier wordt de Server opgezet waarop Clients kunnen connecteren om vervolgens tegen elkaar te spelen
* @author Kaj
*/
public class BomberServer {
public BomberServer() {
waitForPlayers();
}
public static void waitForPlayers() throws Exception {
try {
DatagramSocket serverSocket = new DatagramSocket(9876); //Socket openen
byte[] receiveData = new byte[1024]; //Ontvangen gegevens
byte[] sendData = new byte[1024]; //Te verzenden gegevens
while(true) {
receiveData = new byte[1024];
//Ontvangen data (als die er is) ophalen
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
System.out.println ("Waiting for datagram packet");
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.println ("From: " + IPAddress + ":" + port);
System.out.println ("Message: " + sentence);
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
sendData = new String("Request accepted").getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
serverSocket.send(sendPacket);
}
}
catch(SocketException ex) {
System.out.println("UDP Port 9876 is occupied.");
System.exit(1);
}
}
public static void main(String args[]) {
BomberServer server = new BomberServer();
}
}
尝试运行此代码时,我收到错误“未报告的异常异常;必须被抓住或宣布被抛出”。
我知道这与我放置在我的 waitForPlayers() 方法声明后面的“抛出异常”有关。但是当我删除这个 throws Exception 部分时,我在该行收到一个错误: serverSocket.receive(receivePacket); 'unreporter 异常 IOException; 必须宣布被抛出'所以我想我尝试的两种方法都不是正确的方法。
那么我该怎么做才能正确呢?
真挚地,
卢克索