Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sockets 为什么我会得到null.pointer异常,我确定哪里没有';没有任何空变量_Sockets_Nullpointerexception_Maze - Fatal编程技术网

Sockets 为什么我会得到null.pointer异常,我确定哪里没有';没有任何空变量

Sockets 为什么我会得到null.pointer异常,我确定哪里没有';没有任何空变量,sockets,nullpointerexception,maze,Sockets,Nullpointerexception,Maze,为什么要获取java.lang.NullPointerException?我想我做的一切都是对的。我不明白为什么我会得到这个。 这里是客户端和连接类 public class Server { public static Maze lab; public static Socket s; public static Socket z; public static player human; public static BufferedReader input; public static Ou

为什么要获取java.lang.NullPointerException?我想我做的一切都是对的。我不明白为什么我会得到这个。 这里是客户端和连接类

public class Server {

public static Maze lab;
public static Socket s;
public static Socket z;
public static player human;
public static BufferedReader input;
public static OutputStream os;
public static InputStream is;
public static int n=-1;
public static connections info;
public static ObjectOutputStream oos;


public static void main(String[] args) {
    try{
    ServerSocket Serversocket = new ServerSocket(1900);
    System.out.println("Maze Game Server Started on port " + Serversocket.getLocalPort());
    FileInputStream fis = new FileInputStream("labirintas.cfg");
    ObjectInputStream ois = new ObjectInputStream(fis);
    lab = (Maze) ois.readObject();
    fis.close();
    ois.close();
    info = new connections();
    try {
        while(true){
        try{
        s = Serversocket.accept();
        z = Serversocket.accept();
        System.out.println("Conection from: " + s.getLocalAddress().getHostAddress());
        os = s.getOutputStream();
        is = z.getInputStream();
        oos = new ObjectOutputStream(os);
        oos.writeObject(lab);
        oos.flush();
        n++;
        //is.close();            
        human = new player(n);
        human.start();
        }catch(Exception exception){
            System.out.println("nėra labirinto" + exception.getMessage());
            System.exit(0);
        }finally
        {
            s.close();
        }
        }
    } catch ( Exception ex) {
        System.out.println(ex.getMessage());
    }

}catch(Exception e){
    System.out.println(e.getMessage());
}
}

public static class player extends Thread{
public int x=0;
public int y=0;
public int counter = 0;
public String nick="";

public player(int n){
    x=0;
    y=0;
    counter = n;
    try{
        input = new BufferedReader(new InputStreamReader(is));
        nick = input.readLine();
        System.out.println(counter+" "+x+" "+y+" "+ nick );
        info.info(counter, x, y, nick);
        oos.writeObject(info);
        oos.flush();
        }catch(Exception e){
        System.out.println(e.getStackTrace());
        }
}

public int getcooX(){
    return x;
}

public int getcooY(){
    return y;
}

public void moveUP(){
    x--;
}

public void moveDOWN(){
    x++;
}

public void moveLEFT(){
    y--;
}

public void moveRIGHT(){
    y++;
}

@Override
public void run(){
    try{
        while(true){
            System.out.println(s + " with name: "+ nick + ": " + (s.isConnected()?"true":"false"));
            if (input!=null){
            String command = input.readLine();
            System.out.println(command);
            if(command.startsWith("MOVE_UP")){
                System.out.println("up move");
                if (lab.checkUP(x, y)==false){
                    System.out.println("up accepted");
                    x--;
                    info.info(counter, x, y, nick);
                    oos.writeObject(info);
                    oos.flush();
                }
                if(lab.isItWin(x, y)){
                    System.out.println("Winner");
                    s.close();
                }
            }
            else if(command.startsWith("MOVE_LEFT")){
                System.out.println("left move");
                if (lab.checkLEFT(x, y)==false){
                    System.out.println("left accepted");
                    y--;
                    info.info(counter, x, y, nick);
                    oos.writeObject(info);
                    oos.flush();
                }
                if(lab.isItWin(x, y)){
                    System.out.println("Winner");
                    s.close();

                }
            }
            else if(command.startsWith("MOVE_RIGHT")){
                System.out.println("right move");
                if (lab.checkRIGHT(x, y)==false){
                    System.out.println("right accepted");
                    y++;
                    info.info(counter, x, y, nick);
                    oos.writeObject(info);
                    oos.flush();
                }
                if(lab.isItWin(x, y)){
                    System.out.println("Winner");
                    s.close();
                }
            }
            else if(command.startsWith("MOVE_DOWN")){
                System.out.println("down move");
                if (lab.checkRIGHT(x, y)==false){
                    System.out.println("down accepted");
                    y++;
                    info.info(counter, x, y, nick);
                    oos.writeObject(info);
                    oos.flush();
                }
                if(lab.isItWin(x, y)){
                    System.out.println("Winner");
                    s.close();
                }
            }
            }
        }
    }catch(Exception e){
       System.out.println(e.getMessage());
    }
    }
}
}
公共类客户端实现ActionListener,可序列化{
公共静态JFrame主机;
公共静态JPanel mainP;
公共静态JLabel文本;
公共静态JButton新;
公共静态按钮出口;
公共静态JTextField-nickas;
公共实验室;
公共酒吧;
公共JMenu文件;
公共菜单编辑;
公共项目关闭;
公共框架库提;
公共JLabel[][]标签;
公共JFrame zaidimas;
公共静态迷宫实验室;
公共颜色sienos=颜色为黑色;
公共颜色zaidejo=Color.RED;
公共颜色laimejimo=Color.GREEN;
公共颜色laukeliai=Color.WHITE;
公共int cooX=0;
公共int cooY=0;
公共静态打印输出;
公共静态插座;
公共静态插座f;
公共静态连接信息;
公共静态输入流;
公共静态对象输入流oos;
公共静态void main(字符串[]args){
main=新JFrame(“Pagrindini meniu”);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainP=新的JPanel();
text=新JLabel(“Sveikičia labirintožaidimas.Įveskite savo vardąPasirinkite ką”
+“darysite”,SwingConstants.中心);
text.setVerticalAlignment(SwingConstants.TOP);
新建=新建按钮(“Pradėtižaidimą”);
nickas=新的JTextField();
nickas.setDocument(新的JTextFieldLimit(10));
mainP.setLayout(新的GridBagLayout());
GridBagConstraints c=新的GridBagConstraints();
c、 填充=GridBagConstraints.HORIZONTAL;
c、 gridx=0;
c、 gridy=0;
c、 插图=新插图(10,0,0,0);
mainP.add(文本,c);
c、 gridx=0;
c、 gridy=1;
主要补充(尼卡斯,c);
c、 gridx=0;
c、 gridy=2;
主程序添加(新的,c);
退出=新的JButton(“IšeitišŠaidimo”);
c、 gridx=0;
c、 gridy=3;
主程序添加(出口,c);
main.add(mainP);
主设置尺寸(500500);
main.show();
New.addActionListener(新客户端());
addActionListener(新客户端());
}
@凌驾
已执行的公共无效操作(操作事件e){
对象源=e.getActionCommand();
if(来源等于(“Pradėtižaidimą”)){
字符串nick=nickas.getText();
试一试{
if(nick.isEmpty()){
JOptionPane.showMessageDialog(主“输入您的姓名”、“请输入您的姓名”、JOptionPane.ERROR\u消息);
}
否则{
s=新套接字(“本地主机”,1900);
f=新套接字(“本地主机”,1900);
os=s.getInputStream();
oos=新的ObjectInputStream(os);
lab=(Maze)oos.readObject();
OutputStream=f.getOutputStream();
//os.close();
输出=新的PrintWriter(是,真);
main.show(假);
zaidimas=新JFrame(“Labirito kurimas”);//sukuriu nauja frame Labirito zaidimui
setLayout(新的GridBagLayout());
扎伊迪马斯。挫折背景(颜色。黑色);
GridBagConstraints ck=new GridBagConstraints();//sukuriu nauja GridBagConstraints stiliui kurti
///////////////////// 
zaidimas.setSize(1200,600);
bar=new JMenuBar();//梅尼乌·朱斯塔
文件=新JMenu(“文件”);
编辑=新JMenu(“编辑”);
/////////////////////
添加(文件);
添加(编辑);
add(close=newjmenuitem(“close”);
close.setAccelerator(KeyStroke.getKeyStroke('C',Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
//////////////////
JMenuItem spalvos=新JMenuItem(“Spalvųmeniu”);
编辑.添加(spalvos);
setAccelerator(击键.getKeyStroke('P',Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
/////////////////
ck.gridx=0;//pridedu ja i tokias koordinates
ck.gridy=0;
ck.fill=GridBagConstraints.HORIZONTAL;//IssiTestu horizontaliai
ck.anchor=gridbag.NORTHWEST;
ck.gridwidth=4;
ck.weightx=1.0;
ck.weighty=0.0;
zaidimas.添加(条,ck);
/////////////////////
labirintas=new JPanel();//labirinto面板
labirintas.setLayout(新网格布局(lab.h、lab.v));
ck.gridy=1;
ck.weightx=0.8;
ck.weighty=1.0;
ck.fill=GridBagConstraints.BOTH;
zaidimas.add(拉比林塔斯,ck);
/////////////////////
text=新的JLabel(“联机:”);
ck.gridx=4;
ck.weightx=0.2;
ck.权重=1.0;
ck.fill=GridBagConstraints.BOTH;
ck.anchor=GridBagConstraints.FIRST\u LINE\u START;
添加(文本,ck);
////////
label=new JLabel[lab.h][lab.v];//sukuriu masyva labeliu
////////////////
sienos();
///////////////
标签[0][0]。挫折背景(zaidejo);
///////////////
试一试{
输出println(nick);
在线();
}捕获(例外b){
}
addKeyListener(新的KeyListener(){
@凌驾
公共无效密钥已释放(密钥事件K){
试一试{
if(K.getKeyCode()==KeyEvent.VK_A){
输出println(“向左移动”);
output.flush();
if(lab.checkLEFT(cooX,cooY)=false){
标签[cooX][cooY].setBackground(颜色.白色);
咕咕--;
在线();
}
if(实验室isItWin(cooX,cooY)){
showMessageDialog(主“Winner!”,“You Wind.”,JOptionPane.PLAIN_消息);
System.out.println(“获胜者”);
public class Client implements ActionListener, Serializable{
 public static JFrame main;
 public static JPanel mainP;
 public static JLabel text;
 public static JButton New;
 public static JButton exit;
 public static JTextField nickas;
public JPanel labirintas;
public JMenuBar bar;
public JMenu file;
public JMenu edit;
public JMenuItem close;
public JFrame kurti;
public JLabel[][] label;
public JFrame zaidimas;
public static Maze lab;
public Color sienos = Color.BLACK;
public Color zaidejo = Color.RED;
public Color laimejimo = Color.GREEN;
public Color laukeliai = Color.WHITE;
public int cooX = 0;
public int cooY = 0;
public static PrintWriter output;
public static Socket s;
public static Socket f;
public static connections info;
public static InputStream os;
public static ObjectInputStream oos;

public static void main(String[] args) {
    main = new JFrame("Pagrindinis meniu");
    main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainP = new JPanel();
    text = new JLabel("Sveiki čia labirinto žaidimas. Įveskite savo vardą. Pasirinkite ką"
            + " darysite", SwingConstants.CENTER);
    text.setVerticalAlignment(SwingConstants.TOP);
    New = new JButton("Pradėti žaidimą");
    nickas = new JTextField();
    nickas.setDocument(new JTextFieldLimit(10));

    mainP.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 0;
    c.insets = new Insets(10,0,0,0);
    mainP.add(text, c);

    c.gridx=0;
    c.gridy = 1;
    mainP.add(nickas, c);

    c.gridx = 0;
    c.gridy = 2;
    mainP.add(New, c);

    exit = new JButton("Išeiti iš žaidimo");
    c.gridx = 0;
    c.gridy = 3;
    mainP.add(exit, c);

    main.add(mainP);
    main.setSize(500, 500);
    main.show();

    New.addActionListener(new Client());
    exit.addActionListener(new Client());
}

@Override
public void actionPerformed(ActionEvent e){
    Object source =e.getActionCommand();
    if (source.equals("Pradėti žaidimą")){
        String nick = nickas.getText();
        try{
            if(nick.isEmpty()){
                JOptionPane.showMessageDialog(main, "Enter Your name", "Please Enter Your name", JOptionPane.ERROR_MESSAGE);
            }
            else{
        s = new Socket("localhost",1900);
        f = new Socket("localhost",1900);
        os = s.getInputStream();
        oos = new ObjectInputStream(os);
        lab = (Maze) oos.readObject();
        OutputStream is = f.getOutputStream();
        //os.close();
        output = new PrintWriter(is, true);


        main.show(false);
        zaidimas =new JFrame("Labirinto kurimas");//sukuriu nauja frame labirinto zaidimui
            zaidimas.setLayout(new GridBagLayout());
            zaidimas.setBackground(Color.BLACK);
            GridBagConstraints ck = new GridBagConstraints(); //sukuriu nauja GridBagConstraints stiliui kurti
            ///////////////////// 
            zaidimas.setSize(1200, 600);
            bar = new JMenuBar();//meniu juosta
            file = new JMenu("File");
            edit = new JMenu("Edit");
            /////////////////////
            bar.add(file);
            bar.add(edit);
            file.add(close = new JMenuItem("Close"));
            close.setAccelerator(KeyStroke.getKeyStroke('C', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
            //////////////////
            JMenuItem spalvos = new JMenuItem("Spalvų meniu");
            edit.add(spalvos);
            spalvos.setAccelerator(KeyStroke.getKeyStroke('P', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
            /////////////////
            ck.gridx = 0;//pridedu ja i tokias koordinates
            ck.gridy = 0;
            ck.fill = GridBagConstraints.HORIZONTAL;//issitemptu horizontaliai
            ck.anchor = GridBagConstraints.NORTHWEST;
            ck.gridwidth = 4;
            ck.weightx = 1.0;
            ck.weighty = 0.0;
            zaidimas.add(bar, ck);
            /////////////////////

            labirintas = new JPanel();//labirinto panele
            labirintas.setLayout(new GridLayout(lab.h,lab.v));
            ck.gridy = 1;
            ck.weightx = 0.8;
            ck.weighty = 1.0;
            ck.fill = GridBagConstraints.BOTH;
            zaidimas.add(labirintas, ck);
            /////////////////////
            text = new JLabel("Online:");
            ck.gridx = 4;
            ck.weightx = 0.2;
            ck.weighty=1.0;
            ck.fill = GridBagConstraints.BOTH;
            ck.anchor = GridBagConstraints.FIRST_LINE_START;

            zaidimas.add(text, ck);
            ////////
            label = new JLabel[lab.h][lab.v];//sukuriu masyva labeliu
            ////////////////
            sienos();
            ///////////////
            label[0][0].setBackground(zaidejo);
            ///////////////
            try{
                output.println(nick);
                online();
            }catch(Exception b){

            }

         zaidimas.addKeyListener(new KeyListener(){
               @Override
               public void keyReleased(KeyEvent K){
                   try{
                  if (K.getKeyCode()==KeyEvent.VK_A){
                     output.println("MOVE_LEFT");
                     output.flush();
                     if (lab.checkLEFT(cooX, cooY)==false){
                     label[cooX][cooY].setBackground(Color.white);
                     cooY--;
                     online();
                     }
                     if(lab.isItWin(cooX, cooY)){
                         JOptionPane.showMessageDialog(main, "Winner!", "You Won.", JOptionPane.PLAIN_MESSAGE);
                        System.out.println("Winner");
                        s.close();
                        f.close();
                        System.exit(0);
                    }
                 }
                  else if (K.getKeyCode()==KeyEvent.VK_W){
                        output.println("MOVE_UP");
                        output.flush();
                        if (lab.checkUP(cooX, cooY)==false){
                        label[cooX][cooY].setBackground(Color.white);
                        cooX--;
                        online();
                        }
                        if(lab.isItWin(cooX, cooY)){
                            JOptionPane.showMessageDialog(main, "Winner!", "You Won.", JOptionPane.PLAIN_MESSAGE);
                        System.out.println("Winner");
                        s.close();
                        f.close();
                        System.exit(0);
                        }
                    }
                  else if (K.getKeyCode()==KeyEvent.VK_D){
                     output.println("MOVE_RIGHT");
                     output.flush();
                     if (lab.checkRIGHT(cooX, cooY)==false){
                     label[cooX][cooY].setBackground(Color.white);
                     cooY++;
                     online();
                     }
                     if(lab.isItWin(cooX, cooY)){
                         JOptionPane.showMessageDialog(main, "Winner!", "You Won.", JOptionPane.PLAIN_MESSAGE);
                        System.out.println("Winner");
                        s.close();
                        f.close();
                        System.exit(0);
                    }
                    }
                    if (K.getKeyCode()==KeyEvent.VK_S){
                     output.println("MOVE_DOWN");
                     output.flush();
                     if (lab.checkDOWN(cooX, cooY)==false){
                     label[cooX][cooY].setBackground(Color.white);
                     cooX++;
                     online();
                     }
                     if(lab.isItWin(cooX, cooY)){
                         JOptionPane.showMessageDialog(main, "Winner!", "You Won.", JOptionPane.PLAIN_MESSAGE);
                        System.out.println("Winner");
                        s.close();
                        f.close();
                        System.exit(0);
                    }
                    }
                   }catch(Exception ex){   
                   }
               }
               public void keyPressed(KeyEvent key){}
               public void keyTyped(KeyEvent keyE){}
          });
            ///////////////
            zaidimas.show();

            close.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                        zaidimas.dispose();
                        main.dispose();
                        System.exit(0);
                }
            });
            zaidimas.addWindowListener(new WindowAdapter(){
                @Override
                public void windowClosing(WindowEvent wind){
                   main.show(true);
                   mainP.show(true);
                   try{
                   s.close();
                   f.close();
                   }catch(Exception ex){

                   }
                }
            });
            }
    }catch(UnknownHostException exception){
            JOptionPane.showMessageDialog(main, exception.getMessage()+exception, "Host error", JOptionPane.ERROR_MESSAGE);
            exception.getStackTrace();
        }
        catch(Exception except){
            JOptionPane.showMessageDialog(main, except.getMessage()+except, "Fatal error", JOptionPane.ERROR_MESSAGE);
            except.getStackTrace();
        }
    }
    else if (source.equals("Išeiti iš žaidimo")){
        main.dispose();
        System.exit(0);
    }
}





 //   public void gamer(){//tikrina ar zaidejas yra laimejimo langelija
  //      label[game.getcooX()][game.getcooY()].setBackground(zaidejo);
  //                  if (lab.isItWin(game.getcooX(), game.getcooY())){
  //                      zaidimas.dispose();
  //                      JOptionPane.showMessageDialog(main, "Jūs laimėjote!", "Sveikiname", JOptionPane.ERROR_MESSAGE);
  //                      main.show(true);
  //                      mainP.show(true);
  //                  }
 //   }

    public void sienos(){
        for(int i=0;i<lab.h;i++){
                    for(int j=0; j<lab.v;j++){//ciklas braizyti sienom
                        label[i][j] = new JLabel();
                        int t=0,r=0,bot=0,l = 0;//i sias reiksmes isirasysiu sienu ploti
                        if (i==0){
                           if(lab.checkUP(i, j)) t=5; //tikrina ar borderis, jei borderis, tai storesne siena, jei ne, tai plonesne
                        }
                        else {
                            if(lab.checkUP(i, j)) t=2;
                        } 
                        if (i==lab.h-1){
                            if(lab.checkDOWN(i, j)) bot=5;
                        }
                        else{
                            if(lab.checkDOWN(i, j)) bot=2;
                        }
                        if(j==lab.v-1){
                            if(lab.checkRIGHT(i, j)) r=5;
                        }
                        else{
                            if(lab.checkRIGHT(i, j)) r=2;
                        }
                        if (j==0){
                            if(lab.checkLEFT(i, j)) l=5;  
                        }
                        else{
                        if(lab.checkLEFT(i, j)) l=2;
                    }
                    label[i][j].setBorder(BorderFactory.createMatteBorder(t, l, bot,r , sienos));
                    label[i][j].setOpaque(true); //kad matytusi labelis
                    if(lab.isItWin(i, j)) label[i][j].setBackground(laimejimo);
                    else label[i][j].setBackground(laukeliai);
                    labirintas.add(label[i][j]);
                }
            }
}
public void online(){
    try{
        info = (connections) oos.readObject();
    }catch(Exception e){
    System.out.println(e.getCause());}
    text.setText("Online:");
    for (int i=0;i<info.names.length;i++){
        text.setText(text.getText() + "\n" + info.names[i]);
        label[info.x[i]][info.y[i]].setBackground(Color.gray);
        if(lab.isItWin(info.x[i], info.y[i])) label[info.x[i]][info.y[i]].setBackground(laimejimo);
        label[cooX][cooX].setBackground(Color.white);
    }
}
}


    public class connections {
        public String[] names;
        public int[] x;
        public int[] y;

        public void connections(){
            names = new String[99];
            x = new int[99];
            y = new int[99];
            for (int i=0;i<100;i++){
                names[i]="";
                x[i]=0;
                y[i]=0;
            }
        }

        public void info(int n,int x,int y,String name){
            names[n]=name;
            this.x[n]=x;
            this.y[n]=y;
        }
    }
java.lang.NullPointerException
at client.connections.info(connections.java:24)
at server.Server$player.<init>(Server.java:90)
at server.Server.main(Server.java:57)
public class connections {
    public connections(){
        ...
public connections(){
    names = new String[99];
    x = new int[99];
    y = new int[99];
    for (int i=0;i<99;i++){
        names[i]="";
        x[i]=0;
        y[i]=0;
    }
}
public connections(){
    names = new String[100];
    x = new int[100];
    y = new int[100];
    for (int i=0;i<100;i++){
        names[i]="";
        x[i]=0;
        y[i]=0;
    }
}
public class Connections {
    public Connections(){
        ...