在使用java对象流的时候,首先要保证通信双方各有一个公用的包,里面的内容相同,注意异常的抛出。
相同的包
package common;
public class User implements java.io.Serializable{
private String name;
private String pass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
服务器端
package test1;
//引包
import common.*;
import java.net.*;
import java.io.*;
public class Myserver {
public static void main(String[] args) {
// TODO Auto-generated method stub
Myserver ms = new Myserver();
}
public Myserver()
{
ServerSocket ss;
try {
System.out.println("在9988端口上面监听");
ss = new ServerSocket(9988);
Socket s = ss.accept();
//以对象流读取,假设客户端发送的是User对象
ObjectInputStream iso = new ObjectInputStream(s.getInputStream());
//接收客户端发送的信息
User u = (User)iso.readObject();
System.out.println("接收到的信息" + u.getName() + u.getPass());
//关闭,一定要加上,不然会抛异常
s.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端
package test1;
import common.*;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Myclient {
public static void main(String[] args) {
// TODO Auto-generated method stub
Myclient mc = new Myclient();
}
public Myclient()
{
try {
Socket s = new Socket("127.0.0.1",9988);
//通过ObjectOutputStream给服务器传送对象
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
User u = new User();
u.setName("无邪");
u.setPass("123456");
oos.writeObject(u);
System.out.println("OK");
s.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}