java programming -UDP basic types of transmission networks (int, boolean, string)

Receiving end
Address already in use: Can not bind under the same protocol port can not conflict
1, using DatagramSocket designated port to create a receiving end
2, to prepare a packaged into DatagramPacket package
3, blocking accept packages from the receive (DatagramPacket P);
. 4, analysis data the reduction to the corresponding byte array type
getData () returns a byte array type, getLength () returns the data length, type of int
. 5, the release of resources
* /

public class http{

public static void main(String[]args) throws IOException
{
    System.out.println("接收方启动子...");
    //创建接口
    DatagramSocket server=new DatagramSocket(8888);
    //封装包裹
    byte[] data=new byte[1024*60];
    DatagramPacket packet= new DatagramPacket(data,0,data.length);
    //接受包裹
    server.receive(packet);
    //分析数据
    byte[] datas=packet.getData();
    int len=packet.getLength();

    ByteArrayInputStream bis=new ByteArrayInputStream(datas);
    DataInputStream dis=new DataInputStream(new BufferedInputStream(bis));
    String s=dis.readUTF();
    int age=dis.readInt();
    boolean flag=dis.readBoolean();
    char ch=dis.readChar();

    System.out.println(age+s);

    //关闭资源
    server.close();
    }

Basic types: the transmitting end
1, the transmitting side created DatagramSocket designated port
2, prepare the data must be converted into a byte array, will be transferred into a byte array type base
3, to prepare a packaged DatagramPacket package, requiring a destination (ip address and port)
4, a package sent send (of DatagramPacket P);
. 5, the release of resources

public class client{

public static void main(String[]args) throws IOException
{
    System.out.println("发送方启动中...");
    //创建接口
    DatagramSocket client=new DatagramSocket(9999);
    //准备数据,将数据转成字节数组
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(baos));

    dos.writeUTF("杜雨龙最帅");
    dos.writeInt(18);
    dos.writeBoolean(false);
    dos.writeChar('q');

    dos.flush();

    byte[] datas=baos.toByteArray();
    //封装包裹
    DatagramPacket packet =new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",8888));
    //发送包裹
    client.send(packet);
    //释放资源
    client.close();

}
}

Guess you like

Origin blog.51cto.com/14437184/2432515