java-udp programming

TCP / IP UDP are based on the transport layer; and udp send data loss situation occurs, regardless of the other party sends a data reception is not received, sent in the past to get away;

udp features: the source and destination data encapsulated into packets, do not establish the connection; (of DatagramPacket)

The size of each data reported in the 64K limit within

Because there was no connection, unreliable protocol

Without establishing a connection speed;

We will write the following code generation show UDP

A, client-side

  

public class UDPSocketClient {
    
    public static void main(String[] args) throws Throwable {
    
            //send();
        
            keySend();
    
    }

    private static void keySend() throws Throwable {
         
        try {
            
            //1、创建UDP服务
            DatagramSocket socket=new DatagramSocket();
            
            BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
            
             String message=null;
            
            while((Message = reader.readLine ()) =! null ) { 
                
                
                IF (message.equals ( "886" ))   
                 
                    BREAK ; 
                
                // 2, encapsulating packets                     
                of DatagramPacket = Send new new of DatagramPacket (message.getBytes (), message.getBytes () .length, InetAddress.getByName ( "localhost"), 8088 );
                 // blocking 3, transmission data
                 socket.send (send); 
            } 
            //. 4, the release of resources 
            the Socket.close (); 
            
        } the catch (E a SocketException ) {
             // the TODO Auto-Generated Block the catch 
            e.printStackTrace (); 
        }
        
    }

Two, SERVER end

public  class UDPSocketServer { 
    
    public  static  void main (String [] args) throws the Throwable {
         // the receive (); 
        Keyreceive (); 
    } 

    Private  static  void Keyreceive () throws the Throwable { 
         
        // . 1, and create a designated port udp socket 
        DatagramSocket socket = new new DatagramSocket (8088 ); 
        
        the while ( to true ) {
              // 2, define the data packet to be received 
             byte [] bytes = new new  byte [1024 ]; 
             of DatagramPacket packet= New new of DatagramPacket (bytes, bytes.length); 
             Socket.Receive (Packet); // blocking 
             String Message = new new String (packet.getData (), 0 , packet.getData () length.); 
             System.out.println ( "Server message is received:" + message); 
        } 
        
         
    } 
}

Third, the test results;

First start the server side, and then open the client

The client sends a message

 

The server receives a message

 

 Multi-threaded chat

First, the client

public class UDPSocketClientThread implements Runnable{
    
    private DatagramSocket  datagramSocket;
    public UDPSocketClientThread(DatagramSocket  datagramSocket) {
        this.datagramSocket=datagramSocket;
    }

    @Override
    public void run() {
        
        BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
        
         String message=null;
        
        try {
            while((message=reader.readLine())!=null) {
                
                if(message.equals("886"))  
                 
                    break;
                
                //2、发送数据
                DatagramPacket send=new DatagramPacket(message.getBytes(),message.getBytes().length,InetAddress.getByName("192.168.43.255"), 8088);
                //阻塞式
                this.datagramSocket.send(send);
            }
        } catch (UnknownHostException e) {
            
            e.printStackTrace();
        } catch (IOException e) {
            
            e.printStackTrace();
        }
    }
    
}

Second, the server

public class UDPSocketServerThread implements Runnable{
    
    DatagramSocket socket;
    
    public UDPSocketServerThread(DatagramSocket socket) {
        this.socket=socket;
    }
 

    @Override
    public void run() {
        
        while(true) {
             //2、定义数据 要接收的报文
             byte[] bytes = new byte[1024];
             DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
             try {
                socket.receive(packet);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }//阻塞式
             String message=new String(packet.getData(),0,packet.getData().length);
             InetAddress inetAddress=null;
            try {
                inetAddress = InetAddress.getLocalHost();
                 System.out.println(inetAddress.getHostAddress()+"的消息为:"+message);
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        
    }
 
}

Third, the test run

public class UDPSocketRun {
    
    public static void main(String[] args) throws Throwable {
        DatagramSocket send=new DatagramSocket();
        DatagramSocket receive=new DatagramSocket(8088);
        new Thread(new UDPSocketClientThread(send)).start();
        new Thread(new  UDPSocketServerThread(receive)).start(); 
    }
}

 

 

Guess you like

Origin www.cnblogs.com/hellohero55/p/11992788.html