package info.istlab.ServerTester;
import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Hashtable;
import javax.swing.JOptionPane;
public class UDPServer implements Runnable {
Thread thread;
DatagramSocket socket = null;
public int port;
// 受信したデータを IP アドレスをキーにして保存
Hashtable<String, String> receivedData = new Hashtable<String, String>();
public static void main(String[] args) {
new UDPServer();
}
public UDPServer() {
this(54320);
}
public UDPServer(int _port) {
port = _port;
try {
// サーバーソケットを指定されたポートで作成
socket = new DatagramSocket(port);
System.out.println("[UDP] 近隣ホストのサーバ情報を集めるUDPサーバをポート" + port + "で起動しました。");
System.out.println(getClass().getName() + " [0.0.0.0:" + port + "] started.");
} catch (BindException bex) {
JOptionPane.showMessageDialog(Host.mainhost,
"UDPサーバ起動時に、サーバソケットのバインドに失敗しました。\n\nポート " + port + " は使用されています。\n既存のサービスを停止するか、ポート番号を変更してください。",
"エラー", JOptionPane.ERROR_MESSAGE);
} catch (Exception e) {
e.printStackTrace();
}
start();
}
public void start() {
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void stop() {
socket.close();
}
public void run() {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (thread != null) {
try {
// データグラムパケットを受信
socket.receive(packet);
System.out.println(
"[UDP] " + packet.getAddress().getHostAddress() + ":" + packet.getPort() + " から以下のデータを受信しました。");
// 受信したデータを文字列に変換
String received = new String(packet.getData(), 0, packet.getLength());
receivedData.put(packet.getAddress().getHostAddress(), received);
System.out.println(received);
// 返信メッセージを作成
// String response = "サーバーからの応答: " + received;
// byte[] responseData = response.getBytes();
// // 返信データを送信
// DatagramPacket responsePacket = new DatagramPacket(
// responseData, responseData.length,
// packet.getAddress(), packet.getPort());
// socket.send(responsePacket);
} catch(SocketException sx) {
thread = null;
} catch (Exception e) {
e.printStackTrace();
thread = null;
} finally {
if (socket != null) {
socket.close();
}
}
}
if (socket != null && !socket.isClosed()) {
socket.close();
}
}
}