Java Socket实战之三:传输对象
前面两篇文章介绍了怎样建立Java Socket通信,这一篇说一下怎样使用Java Socket来传输对象。
首先需要一个普通的对象类,由于需要序列化这个对象以便在网络上传输,所以实现java.io.Serializable接口就是必不可少的了,如下:
- packagecom.googlecode.garbagecan.test.socket.sample3;
- publicclassUserimplementsjava.io.Serializable{
- privatestaticfinallongserialVersionUID=1L;
- privateStringname;
- privateStringpassword;
- publicUser(){
- }
- publicUser(Stringname,Stringpassword){
- this.name=name;
- this.password=password;
- }
- publicStringgetName(){
- returnname;
- }
- publicvoidsetName(Stringname){
- this.name=name;
- }
- publicStringgetPassword(){
- returnpassword;
- }
- publicvoidsetPassword(Stringpassword){
- this.password=password;
- }
- }
对于Server端的代码,代码中分别使用了ObjectInputStream和ObjectOutputStream来接收和发送socket中的InputStream和OutputStream,然后转换成Java对象,如下:
- packagecom.googlecode.garbagecan.test.socket.sample3;
- importjava.io.*;
- importjava.net.ServerSocket;
- importjava.net.Socket;
- importjava.util.logging.Level;
- importjava.util.logging.Logger;
- publicclassMyServer{
- privatefinalstaticLoggerlogger=Logger.getLogger(MyServer.class.getName());
- publicstaticvoidmain(String[]args)throwsIOException{
- ServerSocketserver=newServerSocket(10000);
- while(true){
- Socketsocket=server.accept();
- invoke(socket);
- }
- }
- privatestaticvoidinvoke(finalSocketsocket)throwsIOException{
- newThread(newRunnable(){
- publicvoidrun(){
- ObjectInputStreamis=null;
- ObjectOutputStreamos=null;
- try{
- is=newObjectInputStream(newBufferedInputStream(socket.getInputStream()));
- os=newObjectOutputStream(socket.getOutputStream());
- Objectobj=is.readObject();
- Useruser=(User)obj;
- System.out.println("user:"+user.getName()+"/"+user.getPassword());
- user.setName(user.getName()+"_new");
- user.setPassword(user.getPassword()+"_new");
- os.writeObject(user);
- os.flush();
- }catch(IOExceptionex){
- logger.log(Level.SEVERE,null,ex);
- }catch(ClassNotFoundExceptionex){
- logger.log(Level.SEVERE,null,ex);
- }finally{
- try{
- is.close();
- }catch(Exceptionex){}
- try{
- os.close();
- }catch(Exceptionex){}
- try{
- socket.close();
- }catch(Exceptionex){}
- }
- }
- }).start();
- }
- }
Client也和Server端类似,同样使用ObjectOutputStream和ObjectInputStream来处理,如下:
- packagecom.googlecode.garbagecan.test.socket.sample3;
- importjava.io.BufferedInputStream;
- importjava.io.IOException;
- importjava.io.ObjectInputStream;
- importjava.io.ObjectOutputStream;
- importjava.net.Socket;
- importjava.util.logging.Level;
- importjava.util.logging.Logger;
- publicclassMyClient{
- privatefinalstaticLoggerlogger=Logger.getLogger(MyClient.class.getName());
- publicstaticvoidmain(String[]args)throwsException{
- for(inti=0;i<100;i++){
- Socketsocket=null;
- ObjectOutputStreamos=null;
- ObjectInputStreamis=null;
- try{
- socket=newSocket("localhost",10000);
- os=newObjectOutputStream(socket.getOutputStream());
- Useruser=newUser("user_"+i,"password_"+i);
- os.writeObject(user);
- os.flush();
- is=newObjectInputStream(newBufferedInputStream(socket.getInputStream()));
- Objectobj=is.readObject();
- if(obj!=null){
- user=(User)obj;
- System.out.println("user:"+user.getName()+"/"+user.getPassword());
- }
- }catch(IOExceptionex){
- logger.log(Level.SEVERE,null,ex);
- }finally{
- try{
- is.close();
- }catch(Exceptionex){}
- try{
- os.close();
- }catch(Exceptionex){}
- try{
- socket.close();
- }catch(Exceptionex){}
- }
- }
- }
- }
最后测试上面的代码,首先运行Server类,然后运行Client类,就可以分别在Server端和Client端控制台看到接收到的User对象实例了。
原文链接:http://blog.csdn.net/kongxx/article/details/7259827