Socket.accept()抛出空指针异常 [英] Socket.accept() throws null pointer exception

查看:667
本文介绍了Socket.accept()抛出空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个单独的p2p文件共享程序,该程序将接受连接并还充当服务器本身.

I am writing a single p2p file sharing program that will accept connections and also serve as server itself.

正在处理中,但第60行

Its in process but Line: 60

Socket sock1 = tcpSocket.accept();

Socket sock1= tcpSocket.accept();

抛出一个Null指针异常,我不知道怎么了.尝试了一切.

throws a Null pointer Exception and i don't know whats wrong. Tried everything.

import java.net.*;
import java.io.*;


public class echoer implements Runnable {
    int i,backlog;
    public Socket tcpClient= null;
    public ServerSocket tcpSocket= null;
    public echoer(int tcpPort, int udpPort, int backlog) {
        try {
            this.tcpSocket = new ServerSocket(tcpPort,backlog);
            System.out.println("Server connected to "+ InetAddress.getLocalHost() + "on TCP port " + tcpPort + "and UDP port " + udpPort );
            this.backlog= backlog;
            listening();
        }
        catch (SocketTimeoutException s) {
            System.out.println("timeout");
        }
        catch (IOException ioe) {
            System.out.println("could not listen on port 10009");
            System.exit(-1);
        }
}
public echoer () {

}
void listening(){
        try {
                //i++;
                tcpSocket.getInetAddress();
                System.out.println();

                //Thread t1= new Thread((Runnable) new AcceptInput());
                //t1.start();
                //tcpSocket.accept();
                //System.out.println("Connection accepted");
                //messaging();
                Thread t2 = new Thread((Runnable) new echoer());
                t2.start();
            }
            catch (Exception e) {
                System.out.println("Cannot accept connection");
            }
        }

public void Client(String addr, int port) throws IOException 
{
    System.out.println("address= "+ addr+ "port= "+ port);
    tcpClient = new Socket(addr,port);
}
/*void messaging () {
    System.out.println("Starting Thread");
    Thread t = new Thread((Runnable) new echoer());
    t.start();
}*/
public void run() {
    while (true) {
        try {
            //System.out.println("Listening on "+ InetAddress.getLocalHost().getHostAddress() + "on TCP port " + tcpSocket.getLocalSocketAddress());
            Socket sock1= tcpSocket.accept();
            //Client(InetAddress.getLocalHost().getHostAddress(),tcpSocket.getLocalPort());
            System.out.println("Connection accepted");
            ObjectOutputStream out= new ObjectOutputStream(sock1.getOutputStream());
            //Now start the messaging thread nad pass this sock1 to tcpClient
            /*String line;
            System.out.println("Write a message");
            DataInputStream din= new DataInputStream(tcpClient.getInputStream());
            line= din.readUTF();
            if (line == null) {
                din.close();
                tcpClient.close();
                }
            System.out.println("Recvd message:" + line);*/
            if (sock1 != null) {
            tcpSocket.close();
            }
        }
        catch (IOException o) {
            System.out.println("Read Failed");
            }
        }
    }

    /*catch (IOException i) {
        System.out.println("Last statement");
    }
}*/
public static void main(String[] args) {
    new echoer(Integer.parseInt(args[0]),Integer.parseInt(args[1]),5);

}
}

 class AcceptInput implements Runnable {
    String token;
    public void run () {
        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
        try {
            token= br.readLine();
        if (token== "connect" ) {
            System.out.print("Enter IP address: ");
            BufferedReader ip= new BufferedReader(new InputStreamReader(System.in));
            //accept ip and port
            // pass ip and port to tcpclient socket to initiate a connection
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}

推荐答案

这是当前的问题,您调用new Thread((Runnable) new echoer()),这将启动您的线程.

Here's the current problem, you call new Thread((Runnable) new echoer()) and this starts your thread.

但是这会为echoer调用空的默认构造函数,该构造函数当前没有任何实际代码!

However this calls the empty default constructor for echoer which currently has no actual code in it!

因此,即使您一次构造了套接字,在执行之后,您也只需使用所有新套接字创建一个新的echoer实例,然后在该实例上调用run()

So even though you construct the sockets once, after you do that you just create a new instance of echoer with all new sockets and call run() on that

这意味着所有正在运行的套接字都为空,因为它们从未设置过,因此在尝试使用它们时会通过NullPointerException来实现.

This means that all the sockets in run are null because they were never set and therefore through a NullPointerException when you try to use them.

这篇关于Socket.accept()抛出空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆