新手求教!使用序列化做的时候,我的服务器端抛出了空指针异常,该怎么修改呢?
服务器端
package com.imooc;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class ObjectServer {
/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws IOException {
// Socket socket=new Socket("localhost", 8888);
// System.out.println("InetAddress:"+socket.getInetAddress());
ServerSocket serverSocket=new ServerSocket(8888);
Socket socket = null;
InputStream is=null;
OutputStream os = null;
ObjectInputStream ois=null;
BufferedReader br = null;
PrintWriter pw = null;
try {
is=socket.getInputStream(); //【】【】这里就是出错的地方,第34行
ois=new ObjectInputStream(is);
String info;
while((info=br.readLine())!=null){
System.out.println("我是服务器,客户端说:"+info);
}
socket.shutdownInput();
os=socket.getOutputStream();
pw=new PrintWriter(os);
pw.write("欢迎您!");
pw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(is!=null)
is.close();
if(os!=null)
os.close();
if(ois!=null)
ois.close();
if(br!=null)
br.close();
if(pw!=null)
pw.close();
if(socket!=null)
socket.close();
}
}
}
客户端
package com.imooc;
public class User {
private String userName;
private String userKey;
public User(String userName,String userKey){
this.userName=userName;
this.userKey=userKey;
}
}
package com.imooc;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class ObjectClient {
/**
* @param args
*/
public static void main(String[] args) {
try {
Socket socket=new Socket("localhost", 8888);
System.out.println("InetAddress:"+socket.getInetAddress());
OutputStream os=socket.getOutputStream();
//使用ObjectOutputStream对象序列化流,传递对象
ObjectOutputStream oos=new ObjectOutputStream(os);
User user=new User("admin", "123");
oos.writeObject(user);//序列化
socket.shutdownOutput();
BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String info=br.readLine();
while(info!=null){
System.out.println("我是客户端,服务器说:"+info);
// info=br.readLine();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行服务器端ObjectServer类是抛出的异常如图片所示