datagramserver.java
来自「SSD8练习3 传上去大家参考参考 研究研究」· Java 代码 · 共 61 行
JAVA
61 行
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 + =
减小字号Ctrl + -
显示快捷键?