集册 Java实例教程 UDP发送对象

UDP发送对象

欢马劈雪     最近更新时间:2020-01-02 10:19:05

489
UDP发送对象


//package com.nowjava;// 来 自 时代Java - nowjava.com

import java.io.ByteArrayOutputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetSocketAddress;


public class Main {

    public static void send(String ip, int port, Serializable obj) {


        try {

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            ObjectOutputStream oos = new ObjectOutputStream(baos);

            oos.writeObject(obj);


            byte[] buf = baos.toByteArray();

            System.out.println(buf.length);
/** 时代Java 提供 **/

            DatagramPacket dp = new DatagramPacket(buf, buf.length,

                    new InetSocketAddress(ip, port));

            
展开阅读全文