timeserver.java

来自「让初学者了解javaUDP的编程及应用」· Java 代码 · 共 41 行

JAVA
41
字号
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.DateFormat;


public class TimeServer{
	protected static DatagramSocket socket = null;
 //   protected BufferedReader in = null;
     
	public static void main(String []args){
		while(true){
			try {
				socket = new DatagramSocket(5555);
                byte[] buf = new byte[128];

                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                socket.receive(packet);

                String dString = null;
                Date d = new Date();
				dString = DateFormat.getDateTimeInstance().format(d);
            
                buf = dString.getBytes();

		    // send the response to the client at "address" and "port"
                InetAddress address = packet.getAddress();
                int port = packet.getPort();
                packet = new DatagramPacket(buf, buf.length, address, port);
                socket.send(packet);
                System.out.println("Requiring from:" + address.getHostAddress());
            } catch (IOException e) {
                e.printStackTrace();
		      
            }finally {
            	socket.close();
            }
        }
        
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?