writeobject 방법 사용하기

socket은 writeObject 방법으로 직접 통신합니다.
서버측 코드

public void run() {
while (isRunning) {
System.out.println("connect is running");
try {
socket = sSocket.accept();
System.out.println("connect is ok");
oos = new ObjectOutputStream(socket.getOutputStream());
// oos.writeObject(new Integer(1));
while(true){
int size = (list.size()> 10) ? 10 : list.size();
for (int i = 0; i < size; i++) {
Result result = (Result) list.remove(size);
// System.out.println("result: " + result);
oos.writeObject(result);
// System.out.println(" !");
}
}

} catch (Exception e) {
e.printStackTrace();
}
}
}

클라이언트:

class ReadResult extends Thread {

private String ip = "localhost";
private int port = 8889;
Socket socket = null;
private boolean isRunning = true;
BufferedReader reader = null;

public ReadResult() {
try {
socket = new Socket(ip, port);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

public void run() {
ObjectInputStream ois = null;
try {
System.out.println("chatclient test!");
ois = new ObjectInputStream(socket.getInputStream());
while(true){
Result result = (Result) ois.readObject();
System.out.println("name: " + result.getName());
System.out.println("website: " + result.getWebsite());
// System.out.println("list size : " + resultsList.size());
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Object 객체 클래스

public class Result implements Serializable{
String id;
String name;
String content;
String website;

public Result(String id, String name, String content, String website) {
// TODO Auto-generated constructor stub
this.id = id;
this.name = name;
this.content = content;
this.website = website;
}
public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public String getWebsite() {
return website;
}

public void setWebsite(String website) {
this.website = website;
}
}

좋은 웹페이지 즐겨찾기