java中使用socket可以传输对象吗?
就是使用socket对象在客户端和服务器端进行通信。不知道能不能传输对象,比如说字符串数组之类的。我知道的好像只能传送各种各样的字符串哦,如果不行的话,那图像之类的文件要怎么传送过来啊。
------解决方案--------------------当然可以了,不过都要将对象串行化处理,然后从传输两端进行ObjectInputStream和ObjectOutputStream
处理。具体可以google一下,有很多文章说明串行化是如何进行的。
http://www.diybl.com/course/shtiku/2007331/34045.html 这个网址提供了一个简单的例子,自己看看吧,很简单的
------解决方案--------------------import java.net.*;
import java.io.*;
class ObjectServer{
public static void main(String[] args)
throws
IOException{
ServerSocket server=new ServerSocket(5918);
Socket client=server.accept();
ObjectOutputStream out=new ObjectOutputStream(client.getOutputStream());
MyClass myObject=new MyClass();
out.writeObject(myObject);
out.flush();
out.close();
}
}
//classOne==============
imort java.io.*;
public class MyClass implements Serializable{
private String str= "ok ";
private int i=10;
private MyMember mySubObject=new MyMember();
public String getStr(){
return str;
}
public int getInt(){
return i;
}
public MyMember getSubObject(){
return mySubObject;
}
}
//classOne 's member================
import java.io.*;
public class MyMember implements Serializable{ //the member var must implement Serializable
private char[] myArray=new char[]{ 'a ', 'b ', 'c '};
public char[] getArray(){
return myArray;
}
}
//client================
import java.io.*;
import java.net.*;
class ObjectClient{
public static void main(String[] args)
throws Exception{
Socket client=new Socket( "localhost ",5918);
ObjectInputStream in=new ObjectInputStream(client.getInputStream());
MyClass myObject=(MyClass)in.readObject();
System.out.println(myObject.getInt());
System.out.println(myObject.getStr());
char[] myArry=((MyMember)myObject.getSubObject()).getArray();
System.out.println(new String(myArry));
in.close();
}
}
==========================================
转的高手贴,传对象好像要序列化,implements java.io.Serializable,我不懂,帮你顶