你可以用Socket中写入一个ObjectOutputStream 和ObjectInputStream,,,
用JAVA中的,,类锁定,,(那个类我记得不是很清了,如果明天还没有解决,明天和你说)
然后再用前后对应的那个类进行对象定义,然后把对象写入流,然后再用Socket进行传输
用JAVA中的,,类锁定,,(那个类我记得不是很清了,如果明天还没有解决,明天和你说)
然后再用前后对应的那个类进行对象定义,然后把对象写入流,然后再用Socket进行传输
1.序列化所要传输的类,ClassPath中必须包含该类的路径(否则服务器和客户机可能有一方无法找到该类的定义,会抛出ClassNotFoundException的异常)
2.用ObjectOutput和ObjectInput包装自Socket传出和传入的数据流
3.在接收一方一定要捕获ClassNotFoundException的异常,否则程序无法正常执行以下是本人做的实验,由服务器传出一个实例,客户端接受并打印,本人只做了单向流动,稍加改动即可双向传输实例。
[传输类的定义]
import java.io.*;
public class Alien implements Serializable{ //序列化所要传输的类
private int i;
private String str=new String();
public Alien(){}
public Alien(String s){
str=s;}
public String toString(){
return str;
}
}[客户端]
import java.net.*;
import java.io.*;public class JabberClient {
public static void main(String[] args)
throws IOException {
InetAddress addr=
InetAddress.getByName(null);
System.out.println("addr="+addr);
Socket socket= new Socket(addr,JabberSever.PORT);
System.out.println("socket="+socket);
Alien z=new Alien();
try{
ObjectInput in=
new ObjectInputStream(
new DataInputStream(
socket.getInputStream()));
try{ //此处的错误捕获代码一定要有,否则会出错
z=(Alien)in.readObject();
}catch (ClassNotFoundException e)
{System.out.println("Class:"+Alien+"NotFound!");}
System.out.println(z);
}finally{
System.out.println("closing...");
socket.close();
}
}
}
[服务器]
import java.io.*;
import java.net.*;public class JabberSever {
public static final int PORT=8080;
public static void main(String[] args)
throws IOException {
ServerSocket s=new ServerSocket(PORT);
System.out.println("Started: "+s);
try {
Socket socket=s.accept();
try {
System.out.println("Connection accepted:"+socket);
Alien zorcon=new Alien("this");
ObjectOutput out=
new ObjectOutputStream(
new DataOutputStream(
socket.getOutputStream()));
out.writeObject(zorcon);
out.flush();
out.close();
System.out.println(zorcon);
} finally{
System.out.println("Closing...");
socket.close();
}
}finally{
s.close();
}
}
}