udpserver.java

来自「贪食蛇的实现源码」· Java 代码 · 共 69 行

JAVA
69
字号
package com.henry.networkings;

import java.io.*;
import java.net.*; 
import java.util.*; 

public class UDPServer{ 

   public static void main(String args[]) { 
        UDPServer udpServer = new UDPServer(); 
        try { 
            udpServer.go(); 
        } catch (IOException e) { 
            System.out.println ("IOException occured with socket."); 
            System.out.println (e); 
            System.exit(1); 
        } 
    } 

    //This method retrieves the current time on the server 
    public byte[] getTime(){ 
        Date d= new Date(); 
        return d.toString().getBytes(); // String -> byte[]
    } 

   // Main server loop. 
    public void go() throws IOException { 
        DatagramSocket datagramSocket=null; 

        DatagramPacket inDataPacket=null; // Datagram packet from the client 

        DatagramPacket outDataPacket=null; // Datagram packet to the client 

        InetAddress clientAddress=null; // Client return address 

        int clientPort; // Client return port 
        byte[] msg= new byte[10]; // Incoming data buffer. Ignored. 
        byte[] time; // Stores retrieved time 
  
        // 1.  create datagram socket to allocate a socket to a port for requests. 
         datagramSocket = new DatagramSocket(9000); //port 8000
         System.out.println("!!at UDPServer localport is: " + datagramSocket.getLocalPort()); 
          
        while(true) { 
            // 2. Set up receiver packet. 
            inDataPacket = new DatagramPacket(msg, msg.length); 

            // 3. get data packet from client
            datagramSocket.receive(inDataPacket);

            // 4. Retrieve incoming packet's address information 获得对方的地址
            clientAddress = inDataPacket.getAddress(); 
            clientPort = inDataPacket.getPort(); 
            System.out.println("client HostAddress is: "+clientAddress.getHostAddress()+ " clientPort is : "+ clientPort  ); 
            
            time = getTime();   // call getTime() to get bytes of the current time from operating System.
  
            //5. set up a datagram to be sent to the client
            outDataPacket = new DatagramPacket(time, time.length, clientAddress, clientPort); 
  
            //6. finally send the packet to client 
            datagramSocket.send(outDataPacket); 
        } 
         
    } 
  
    
 } 

⌨️ 快捷键说明

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