1. 程式人生 > >Java Socket實戰傳輸壓縮物件

Java Socket實戰傳輸壓縮物件

有些情況下比如網路環境不好或者物件比較大的情況下需要把資料物件進行壓縮然後在傳輸,此時就需要壓縮這些物件流,此時就可以GZIPInputStream和GZIPOutputStream來處理一下socket的InputStream和OutputStream。

仍然需要一個實現了java.io.Serializable介面的簡單Java物件

[java] view plaincopyprint?
  1. package com.googlecode.garbagecan.test.socket.sample4;  
  2. publicclass User implements java.io.Serializable {  
  3. privatestaticfinallong serialVersionUID = 1L;  
  4. private String name;  
  5. private String password;  
  6. public User() {  
  7.     }  
  8. public User(String name, String password) {  
  9. this.name = name;  
  10. this.password = password;  
  11.     }  
  12. public String getName() {  
  13. return name;  
  14.     }  
  15. publicvoid setName(String name) {  
  16. this.name = name;  
  17.     }  
  18. public String getPassword() {  
  19. return password;  
  20.     }  
  21. publicvoid setPassword(String password) {  
  22. this.password = password;  
  23.     }  
  24. }  
package com.googlecode.garbagecan.test.socket.sample4;

public class User implements java.io.Serializable {
	private static final long serialVersionUID = 1L;
	private String name;
	private String password;

	public User() {
		
	}
	
	public User(String name, String password) {
		this.name = name;
		this.password = password;
	}
	
	public String getName() {
		return name;
	}

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

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
}
在Server端使用,socket的InputStream首先被包裝成GZIPInputStream,然後又被包裝成ObjectInputStream,而socket的OutputStream首先被包裝成GZIPOutputStream,然後又被包裝成ObjectOutputStream,如下: [java] view plaincopyprint?
  1. package com.googlecode.garbagecan.test.socket.sample4;  
  2. import java.io.IOException;  
  3. import java.io.ObjectInputStream;  
  4. import java.io.ObjectOutputStream;  
  5. import java.net.ServerSocket;  
  6. import java.net.Socket;  
  7. import java.util.logging.Level;  
  8. import java.util.logging.Logger;  
  9. import java.util.zip.GZIPInputStream;  
  10. import java.util.zip.GZIPOutputStream;  
  11. publicclass MyServer {  
  12. privatefinalstatic Logger logger = Logger.getLogger(MyServer.class.getName());  
  13. publicstaticvoid main(String[] args) throws IOException {  
  14.         ServerSocket server = new ServerSocket(10000);  
  15. while (true) {  
  16.             Socket socket = server.accept();  
  17.             socket.setSoTimeout(10 * 1000);  
  18.             invoke(socket);  
  19.         }  
  20.     }  
  21. privatestaticvoid invoke(final Socket socket) throws IOException {  
  22. new Thread(new Runnable() {  
  23. publicvoid run() {  
  24.                 GZIPInputStream gzipis = null;  
  25.                 ObjectInputStream ois = null;  
  26.                 GZIPOutputStream gzipos = null;  
  27.                 ObjectOutputStream oos = null;  
  28. try {  
  29.                     gzipis = new GZIPInputStream(socket.getInputStream());  
  30.                     ois = new ObjectInputStream(gzipis);  
  31.                     gzipos = new GZIPOutputStream(socket.getOutputStream());  
  32.                     oos = new ObjectOutputStream(gzipos);  
  33.                     Object obj = ois.readObject();  
  34.                     User user = (User)obj;  
  35.                     System.out.println("user: " + user.getName() + "/" + user.getPassword());  
  36.                     user.setName(user.getName() + "_new");  
  37.                     user.setPassword(user.getPassword() + "_new");  
  38.                     oos.writeObject(user);  
  39.                     oos.flush();  
  40.                     gzipos.finish();  
  41.                 } catch (IOException ex) {  
  42.                     logger.log(Level.SEVERE, null, ex);  
  43.                 } catch(ClassNotFoundException ex) {  
  44.                     logger.log(Level.SEVERE, null, ex);  
  45.                 } finally {  
  46. try {  
  47.                         ois.close();  
  48.                     } catch(Exception ex) {}  
  49. try {  
  50.                         oos.close();  
  51.                     } catch(Exception ex) {}  
  52. try {  
  53.                         socket.close();  
  54.                     } catch(Exception ex) {}  
  55.                 }  
  56.             }  
  57.         }).start();  
  58.     }  
  59. }  
package com.googlecode.garbagecan.test.socket.sample4;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class MyServer {

	private final static Logger logger = Logger.getLogger(MyServer.class.getName());
	
	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(10000);

		while (true) {
			Socket socket = server.accept();
			socket.setSoTimeout(10 * 1000);
			invoke(socket);
		}
	}

	private static void invoke(final Socket socket) throws IOException {
		new Thread(new Runnable() {
			public void run() {
				GZIPInputStream gzipis = null;
				ObjectInputStream ois = null;
				GZIPOutputStream gzipos = null;
				ObjectOutputStream oos = null;
				
				try {
					gzipis = new GZIPInputStream(socket.getInputStream());
					ois = new ObjectInputStream(gzipis);
					gzipos = new GZIPOutputStream(socket.getOutputStream());
					oos = new ObjectOutputStream(gzipos);

					Object obj = ois.readObject();
					User user = (User)obj;
					System.out.println("user: " + user.getName() + "/" + user.getPassword());

					user.setName(user.getName() + "_new");
					user.setPassword(user.getPassword() + "_new");

					oos.writeObject(user);
					oos.flush();
					gzipos.finish();
				} catch (IOException ex) {
					logger.log(Level.SEVERE, null, ex);
				} catch(ClassNotFoundException ex) {
					logger.log(Level.SEVERE, null, ex);
				} finally {
					try {
						ois.close();
					} catch(Exception ex) {}
					try {
						oos.close();
					} catch(Exception ex) {}
					try {
						socket.close();
					} catch(Exception ex) {}
				}
			}
		}).start();
	}
}
Client也和Server端類似,同樣要不socket的XXXStream包裝成GZIPXXXStream,然後再包裝成ObjectXXXStream,如下: [java] view plaincopyprint?
  1. package com.googlecode.garbagecan.test.socket.sample4;  
  2. import java.io.IOException;  
  3. import java.io.ObjectInputStream;  
  4. import java.io.ObjectOutputStream;  
  5. import java.net.InetSocketAddress;  
  6. import java.net.Socket;  
  7. import java.net.SocketAddress;  
  8. import java.util.logging.Level;  
  9. import java.util.logging.Logger;  
  10. import java.util.zip.GZIPInputStream;  
  11. import java.util.zip.GZIPOutputStream;  
  12. publicclass MyClient {  
  13. privatefinalstatic Logger logger = Logger.getLogger(MyClient.class.getName());  
  14. publicstaticvoid main(String[] args) throws Exception {  
  15. for (int i = 0; i < 10; i++) {  
  16.             Socket socket = null;  
  17.             GZIPOutputStream gzipos = null;  
  18.             ObjectOutputStream oos = null;  
  19.             GZIPInputStream gzipis = null;  
  20.             ObjectInputStream ois = null;  
  21. try {  
  22.                 socket = new Socket();  
  23.                 SocketAddress socketAddress = new InetSocketAddress("localhost"10000);   
  24.                 socket.connect(socketAddress, 10 * 1000);  
  25.                 socket.setSoTimeout(10 * 1000);  
  26.                 gzipos = new GZIPOutputStream(socket.getOutputStream());  
  27.                 oos = new ObjectOutputStream(gzipos);  
  28.                 User user = new User("user_" + i, "password_" + i);  
  29.                 oos.writeObject(user);  
  30.                 oos.flush();  
  31.                 gzipos.finish();  
  32.                 gzipis = new GZIPInputStream(socket.getInputStream());  
  33.                 ois = new ObjectInputStream(gzipis);  
  34.                 Object obj = ois.readObject();  
  35. if (obj != null) {  
  36.                     user = (User)obj;  
  37.                     System.out.println("user: " + user.getName() + "/" + user.getPassword());  
  38.                 }  
  39.             } catch(IOException ex) {  
  40.                 logger.log(Level.SEVERE, null, ex);  
  41.             } finally {  
  42. try {  
  43.                     ois.close();  
  44.                 } catch(Exception ex) {}  
  45. try {  
  46.                     oos.close();  
  47.                 } catch(Exception ex) {}  
  48. try {  
  49.                     socket.close();  
  50.                 } catch(Exception ex) {}  
  51.             }  
  52.         }  
  53.     }  
  54. }  
package com.googlecode.garbagecan.test.socket.sample4;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class MyClient {
	
	private final static Logger logger = Logger.getLogger(MyClient.class.getName());
	
	public static void main(String[] args) throws Exception {
		for (int i = 0; i < 10; i++) {
			Socket socket = null;
			GZIPOutputStream gzipos = null;
			ObjectOutputStream oos = null;
			GZIPInputStream gzipis = null;
			ObjectInputStream ois = null;
			
			try {
				socket = new Socket();
				SocketAddress socketAddress = new InetSocketAddress("localhost", 10000); 
				socket.connect(socketAddress, 10 * 1000);
				socket.setSoTimeout(10 * 1000);
				
				gzipos = new GZIPOutputStream(socket.getOutputStream());
				oos = new ObjectOutputStream(gzipos);
				User user = new User("user_" + i, "password_" + i);
				oos.writeObject(user);
				oos.flush();
				gzipos.finish();
				
				gzipis = new GZIPInputStream(socket.getInputStream());
				ois = new ObjectInputStream(gzipis);
				Object obj = ois.readObject();
				if (obj != null) {
					user = (User)obj;
					System.out.println("user: " + user.getName() + "/" + user.getPassword());
				}
			} catch(IOException ex) {
				logger.log(Level.SEVERE, null, ex);
			} finally {
				try {
					ois.close();
				} catch(Exception ex) {}
				try {
					oos.close();
				} catch(Exception ex) {}
				try {
					socket.close();
				} catch(Exception ex) {}
			}
		}
	}
}


最後測試上面的程式碼,首先執行Server類,然後執行Client類,就可以分別在Server端和Client端控制檯看到接收到的User物件例項了。