首页 » Program » Java » 正文

java socket udp

Udpserver.java:

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Udpserver {
    public static void main(String[] args) throws Exception {

        System.out.println("udp server is running......");
        String str_send = "hi udpclient";       
        DatagramSocket se = new DatagramSocket(2016);
        byte[] by = new byte[1024];
        DatagramPacket dp = new DatagramPacket(by,1024);
        
        while (true) {
            se.receive(dp);
            System.out.println("the message from client is: \n");
            String str_receive = new String(dp.getData(),0,dp.getLength());
            System.out.println(str_receive);
            DatagramPacket se_send = new DatagramPacket(str_send.getBytes(),str_send.length(),dp.getAddress(),dp.getPort());
            se.send(se_send);
            dp.setLength(1024);
        }
        //se.close();
    }
}
    

Udpclient.java:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Udpclient {
    public static void main(String[] args) throws Exception {
        DatagramSocket ds = new DatagramSocket();
        String str = "hi server";
        DatagramPacket dp = new DatagramPacket(str.getBytes(),str.length(),InetAddress.getByName("localhost"),2016);
        ds.send(dp);
        byte[] by = new byte[1024];
        DatagramPacket dp2 = new DatagramPacket(by,1024);
        ds.receive(dp2);
        System.out.println(new String(by,0,dp2.getLength()));
        ds.close();
    }
}

Comment