Employee
package 소켓시리얼서버;
import java.io.Serializable;
public class Employee implements Serializable {
String name;
String addr;
String jumin;
String phone;
public Employee(String name, String addr, String jumin, String phone) {
this.name = name;
this.addr = addr;
this.jumin = jumin;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getJumin() {
return jumin;
}
public void setJumin(String jumin) {
this.jumin = jumin;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Server
- ObjectOutputStream : 파일이나 네트워크로 데이터를 전달하기 위해 직렬화를 수행합니다.
- writeObject() :
package 소켓시리얼서버;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketSerialServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(5433);
while(true) {
System.out.println("서버 실행 중..");
Socket socket = serverSocket.accept();
OutputStream outputStream = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(outputStream);
Employee emp = new Employee("우영우", "서울시 강남구", "863312-1111111", "010-5006-1234");
oos.writeObject(emp);
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
Client
- ObjectInputStream : 역직렬화 수행(소켓으로 부터 바이트 스트림 얻어 역직렬화)
- readObject()
package 소켓시리얼클라이언트;
import 소켓시리얼서버.Employee;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ConnectException;
import java.net.Socket;
public class SocketSerialClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 5433);
InputStream inputStream = socket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(inputStream);
Employee emp = (Employee) ois.readObject();
System.out.println("이름 : " + emp.getName());
System.out.println("주소 : " + emp.getAddr());
System.out.println("주민번호 : " + emp.getJumin());
System.out.println("전화번호 : " + emp.getPhone());
ois.close();
socket.close();
} catch (ConnectException e) {
System.out.println("연결실패 !!!!!");
} catch (Exception e ) {
e.printStackTrace();
}
}
}