java programming -UDP- reference network (object) type transmission

public class my implements java.io.Serializable {

public void rr()
{
    System.out.println("杜雨龙最帅a");
}
}

Reference type 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 of data, reduced 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, ClassNotFoundException
{
    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();

    ObjectInputStream ois=new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(datas)));
    Object r=ois.readObject();

    if(r instanceof my)
    {
        my m=(my)r;
        m.rr();
    }

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

}
}

Reference Type: transmitting end
1, the transmitting side created DatagramSocket designated port
2, prepare the data must be converted into a byte array, reference will turn into a byte array type
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 bos=new ByteArrayOutputStream();
    ObjectOutputStream oos=new ObjectOutputStream(new BufferedOutputStream(bos));

    my f=new my();
    oos.writeObject(f);

    oos.flush();

    byte[] datas=bos.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/2432521