日期:2014-05-20 浏览次数:20736 次
for (int i = 0; i < 10; i++) { ping = new Ping(); sendMessage(InetAddress.getByName("localhost"), Integer.parseInt(port), ping); } public void sendMessage(InetAddress receiveHost, int receivePort, Ping message) throws IOException { try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream(bout); oout.writeObject(message); // 序列化对象 oout.flush(); byte[] sendBuff = bout.toByteArray(); // 转化为字节数组 DatagramPacket datagram = new DatagramPacket(sendBuff, sendBuff.length, receiveHost, receivePort); DatagramSocket socket = new DatagramSocket(); socket.send(datagram); // 通过DatagramPacket发送对象 } catch (Exception ex) { ex.printStackTrace(); } }
Ping p = receiveMessage(); public Ping receiveMessage() throws Exception { byte[] receiveBuff = new byte[1024]; DatagramPacket datagram = new DatagramPacket(receiveBuff, 1024); DatagramSocket socket = new DatagramSocket(Integer.parseInt(port)); socket.receive(datagram); Ping message = new Ping(); try { ByteArrayInputStream bint = new ByteArrayInputStream(receiveBuff); ObjectInputStream oint = new ObjectInputStream(bint); message = (Ping) oint.readObject(); // 反序列化,恢复对象 } catch (Exception ex) { ex.printStackTrace(); } return message; }