UDP传递序列化对象
写了一个UDP传递对象的简单例子
?
服务端:
?
package com.udp;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.net.DatagramPacket;import java.net.DatagramSocket;public class UDPServer {public static void main(String[] args) throws IOException {DatagramSocket ds = new DatagramSocket(8081);byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf, buf.length);while (true) {System.out.println("for receive....");ds.receive(dp);Student s = (Student)b2o(dp.getData());System.out.println(s.name);}}public static Object b2o(byte[] buffer) {Object obj = null;try {ByteArrayInputStream buffers = new ByteArrayInputStream(buffer);ObjectInputStream in = new ObjectInputStream(buffers);obj = in.readObject();in.close();} catch (Exception e) {System.out.println("error");}return obj;}}
?
客户端:
package com.udp;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.InetSocketAddress;public class UDPClient {public static void main(String[] args) throws IOException {InetSocketAddress isa = new InetSocketAddress(InetAddress.getByName("192.168.1.102"), 8081);DatagramSocket ds = new DatagramSocket();Student student = new Student();student.name = "denghong";DatagramPacket dp = new DatagramPacket(o2b(student), o2b(student).length, isa);ds.send(dp);}public static byte[] o2b(Student s) {ByteArrayOutputStream buffers = new ByteArrayOutputStream();try {ObjectOutputStream out = new ObjectOutputStream(buffers);out.writeObject(s);out.close();} catch (Exception e) {System.out.println("error");return null;}return buffers.toByteArray();}}
?
序列化对象
package com.udp;import java.io.Serializable;public class Student implements Serializable{private static final long serialVersionUID = -5971668520303705956L;public String name;}?