📄 datagramserver.java
字号:
import java.net.*;
import java.io.*;
//DatagramServer
public class DatagramServer{
//UDP port to which service is bound
public static final int SERVICE_PORT = 7;
//Max size of packet
public static final int SIZE = 1;
//socket used for reading and writing UDP packets
private DatagramSocket socket;
public DatagramServer(){
try{
//Bind to the specified UDP port, to listen for incoming data packets
socket = new DatagramSocket(SERVICE_PORT);
System.out.println("Server active on port " + socket.getLocalPort());
}catch(Exception e){
System.err.println("Unable to bind port");
}
}
public void serviceClients(){
//Creat a buffer large enough for incoming packets
byte[] buffer = new byte[SIZE];
for(;;){
try{
//Creat a DatagramPacket for reading UDP packets
DatagramPacket packet = new DatagramPacket(buffer, SIZE);
//Receive incoing pakcets
socket.receive(packet);
System.out.println("Packet receive from " + packet.getAddress() + ":"+ packet.getPort());
//Echo the packet back - address and port are already set for us!
socket.send(packet);
}catch(IOException ioe){
System.err.println("Error: "+ ioe);
}
}
}
public static void main(String args[]){
DatagramServer server = new DatagramServer();
server.serviceClients();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -