首页 > 代码库 > UDP编程案例

UDP编程案例

package wabgki;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class KeHu {


    public static void main(String[] args) throws IOException {

      InetAddress a=InetAddress.getLocalHost();
        Socket b=new Socket(a,8888);
        PrintWriter pw=new PrintWriter(b.getOutputStream());
        pw.println("好久不见,别来无恙");
        pw.flush();    
        System.out.println("客户端连接成功");
        b.close();

    }

}
package lingyige;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class ClientB {

    public static void main(String[] args) throws Exception {
        // 收包
        
        //1.创建一个DatagramSocket
        DatagramSocket ds=new DatagramSocket(10000);
        //2.收包,它是一个阻塞方法
        byte[]b=new byte[100];
        DatagramPacket dp=new DatagramPacket(b, 100);
        System.out.println("准备接受中");
        ds.receive(dp);
        String str=new String(b,0,dp.getLength());
        System.out.println("信息收到,内容是:"+str);
        //3.关闭

    }

}

 

UDP编程案例