출처

위 기사는 Object serialization 를 사용하여 object를 로컬에 파일로 저장하거나 socket으로 전송하는 단순한 example 을 보여주고 있다. java.io.Serializable 객체를 implement 한 클래스를 소켓으로 어떻게 송/수신 한는지 보여주는 샘플을 간단히 정리해 보았다.

Server
ObjectInputStream   : readObject() 메소드를 사용하여 input stream 객체를 reading 한다.
ObjectOutputStream : writeObject() 메소드를 사용하여 output stream 객체를 writing 한다.

ObjectServer.java
- 무조건 요청을 받아주는 무식한 서버.
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ObjectServer extends Thread {

    private ServerSocket serverSocket;
   
    public ObjectServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        this.start();
    }
   
    public void run() {
        while(true) {           
            Socket client;
            try {
                System.out.println("Waiting for connections.");
                client = serverSocket.accept();
                System.out.println("Accepted a connection from: "+client.getInetAddress());
                WorkerThread c = new WorkerThread(client);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           
        }

    }
}

WorkerThread.java
- 요청을 처리하고 응답값을 보내는 worker thread.
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import study.socket.serializing.ResponseVo;
import study.socket.serializing.RequestVo;

public class WorkerThread extends Thread {
    private Socket client = null;
    // read stream
    private ObjectInputStream ois = null;
    // write stream
    private ObjectOutputStream oos = null;
       
    public WorkerThread() {}

    public WorkerThread(Socket clientSocket) {
        client = clientSocket;
       
        try {
            ois = new ObjectInputStream(client.getInputStream());
            oos = new ObjectOutputStream(client.getOutputStream());
        } catch(Exception e1) {
            try {
                client.close();
            }catch(Exception e) {
                System.out.println(e.getMessage());
            }
            return;
        }
        this.start();
    }
   
    public void readObject() throws IOException, ClassNotFoundException {
        RequestVo requestVo = (RequestVo) ois.readObject();
       
        System.out.println("id:"+requestVo.getId());
        System.out.println("msg:"+requestVo.getMsg());
    }
   
    public void wirteObject() throws IOException {
        ResponseVo responseVo = new ResponseVo();
        responseVo.setId("response id");
        responseVo.setMsg("응답값 전송했음.. 알아서 처리하삼.");
       
        oos.writeObject(responseVo);
    }
   
    public void run() {
       
        try {
            readObject();
            wirteObject();

            oos.flush();
            // close streams and connections
            ois.close();
            oos.close();
            client.close();
        } catch(Exception e) {}              
            try {
                ois.close();
                oos.close();
                client.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           }
    }

Serializing Custom Classes
Serializable interface 를 implements 한 custom class 를 작성한다.

RequestVo.java
- 요청 객체
import java.io.Serializable;

public class RequestVo implements Serializable {

    private String id;
    private String msg;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }  
}

ResponseVo.java
- 응답 객체
import java.io.Serializable;

public class ResponseVo implements Serializable {

    private String id;
    private String msg;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
}

Client

ObjectClient.java
import java.io.*;
import java.net.*;
import java.util.*;

import study.socket.serializing.ResponseVo;
import study.socket.serializing.RequestVo;

public class ObjectClient {

    public static void main(String argv[]) {
          ObjectOutputStream oos = null;
          ObjectInputStream ois = null;
          Socket socket = null;

          try {
            // open a socket connection
            socket = new Socket("127.0.0.1", 20001);
            // open I/O streams for objects
            oos = new ObjectOutputStream(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());
           
            // send an object to the server
            RequestVo requestVo = new RequestVo();
            requestVo.setId("request id");
            requestVo.setMsg("요청했다.. 빨리 보내라 오바.");           
            oos.writeObject(requestVo);
           
            // read an object from the server
            ResponseVo rcvVo = (ResponseVo) ois.readObject();
            System.out.println("id:" + rcvVo.getId());
            System.out.println("msg:" + rcvVo.getMsg());
            oos.close();
            ois.close();
          } catch(Exception e) {
            System.out.println(e.getMessage());
          }
       }
}


'java > socket' 카테고리의 다른 글

DataInputStream 에서 전체 byte[] 읽기  (0) 2012.06.29
Posted by 짱가쟁이