采用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;
	}
}

你可能感兴趣的:(thread,socket)