在学习使用JAVA做网络时需要用ObjectInputStream和ObjectOutputStream从客户端转递一个对象到服务器,却遇到一个奇怪的问题。源码如下:
服务器端:
public class Server
{
class Msg implements Serializable
{
String s1;
String s2;
}
Server()
{
try
{
ServerSocket server=new ServerSocket(6666);
Socket s=server.accept();
ObjectInputStream ois=new ObjectInputStreams.getInputStream());
Msg temp=new Msg();
temp=(Msg)ois.readObject();
System.out.println(temp.s1);
System.out.println(temp.s2);
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String s[])
{
new Server();
}
}
客户端:
public class Client
{
class Msg implements Serializable
{
String s1;
String s2;
}
Client()
{
try
{
Socket s=new Socket("127.0.0.1",6666);
ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());
Msg temp=new Msg();
temp.s2="1";
temp.s2="2";
oos.writeObject(temp);
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String s[])
{
new Client();
}
}
运行后在客户端显示一个"java.io.NotSerializableException: Client"异常,在服务器端显示一个“java.net.SocketException: Connection reset”异常。
请问各位高手这个问题应该怎么解决。
你传送的对象必须Serializable
public class Server implements Serializable
{
class Msg {
//..........
}
}
//....
搂主的程序有一个问题
两个类中Msg类 并不是一个类 反序列化的时候会抛错的
其他的地方没有问题
把Msg类改成public类 就没问题了
我的一点建议
将公用的message提出来,不要用内部类,应为那时两个不同的对象
Message:
public class Msg implements java.io.Serializable{
String s1;
String s2;
}
Server:
public class Server
{
Server()
{
try
{
ServerSocket server=new ServerSocket(6666);
Socket s=server.accept();
ObjectInputStream ois=new ObjectInputStream(s.getInputStream());
Msg temp=new Msg();
temp=(Msg)ois.readObject();
System.out.println(temp.s1);
System.out.println(temp.s2);
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String s[])
{
new Server();
}
}
Client:
public class Client {
Client()
{
try
{
Socket s=new Socket("127.0.0.1",6666);
ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());
Msg temp=new Msg();
temp.s2="1";
temp.s2="2";
oos.writeObject(temp);
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String s[])
{
new Client();
}
}
client类也要implements Serializable