日期:2014-05-20  浏览次数:21522 次

运行服务器端,抛出异常Exception in thread "Thread-0" java.lang.NullPointerException at com
运行服务器端。抛出空指针异常
出现异常的 语句是 关闭输入流ois.close;



package com.pb.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

import com.pb.entity.Book;
import com.pb.entity.Member;
import com.pb.util.Datas;
import com.pb.util.SysConstants;
import com.pb.util.Tools;

public class ServerContextListener extends Thread {

/**
* @param args
*/
public static void main(String[] args) {
new ServerContextListener().start();
}
public void run(){
System.out.println("服务器端启动");
//创建服务器socket相关实例
ServerSocket serverSocket = null;
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null ;
try {
// 创建Socket对象
serverSocket = new ServerSocket(Integer.parseInt(Tools
.getValue(SysConstants.SYS_LISTENERPORT)));
while(true){
// 获取客户端Socket对象
socket = serverSocket.accept();
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
//创建服务器端服务类对象
ServerService serverService = new ServerService();
//获取获取客户端请求的对象
Datas datas = (Datas) ois.readObject();
// 判断客户端请求的操作
if (SysConstants.SYS_LOGIN.equals(datas.getFlag())) {
// 登录
String username = datas.getMember().getUsername();
String password = datas.getMember().getPassword();
Member member = serverService.doLogin(username, password);
if (member == null) {
datas.setFlag(SysConstants.SYS_ERROR);
} else {
datas.setMember(member);
datas.setFlag(SysConstants.SYS_SUCCESS);
}
}else if(SysConstants.SYS_ENROLL.equals(datas.getFlag())){
//注册
String username = datas.getMember().getUsername();
String password = datas.getMember().getPassword();
Member member = serverService.enroll(username, password);
if(member==null){
datas.setFlag(SysConstants.SYS_ERROR);
}else{
datas.setMember(member);
datas.setFlag(SysConstants.SYS_SUCCESS);
}
}else
oos.writeObject(datas);
oos.flush();
socket.shutdownOutput();
}

}catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
ois.close();
oos.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("服务器终止");
}
}


------解决方案--------------------
空指针异常之前是不是应该还有个别的什么异常?
------解决方案--------------------
应该前面有异常把,所以ois未实例化
------解决方案--------------------
try {
ois.close();
oos.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
ois有可能指向null 你都加个if判断非空在去close