UDP 전송 시리얼화된 객체

2676 단어 서열화
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;
	
}

좋은 웹페이지 즐겨찾기