套接字未连接

时间:2012-10-03 21:44:59

标签: java sockets networking network-programming nullpointerexception

我的问题如下:我有以下客户端类:

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;


public class Client {

    public final int portNumber = 6040;
    public Socket socket;
    private PrintWriter pw;
    /**
     * @param args
     * @throws IOException 
     */
    public void connect() throws IOException{


        // du kan vælge at bruge inetadressen til at connecte i socketet.
        InetAddress adr = InetAddress.getByName("localhost");
        socket = new Socket("localhost", portNumber);
        pw = new PrintWriter(socket.getOutputStream());
        pw.println("Connected waiting for input");
        pw.flush();

    }
    /**
     * This method sends the message (that the client(chat person) writes to the user)
     * @param x
     * @throws NullPointerException
     * @throws IOException 
     */
    public void SendChat(String x) throws NullPointerException{
            pw.print(x);
            pw.flush(); 


    }
    public int sendCommando(int id) throws IOException{

         PrintWriter pw = new PrintWriter(socket.getOutputStream());
        pw.print(id);

        /*
         * this part of the program sends a command to the server if the command is 1 then 1 is = Connect.
         * the program then ask the server is the server is full or is it ok to connect? 
         * if the response is not 10 then the program will allow a connection to happen the return type will be the Id of which 
         * the chat person becomes!
         */

        // should the method return 0 the Application will do NOTHING!
        switch (id) {
        case 1:
    int k = reciveCommando();
            if (k== 10) {
                return 10;
            }else if (k<= 3) {
                return k;
            }else {

            return 10;
            }
            /*
             * Closes the connection with the server!
             */
        case 3:

            socket.close();
            return 0;

        default:
            return 0;
        }

    }
    /*
     * this method recives a command from the server! the comands can be found in the ChatCommands.txt
     * returns the command as an integer!
     */
    public int reciveCommando() throws IOException{
        Scanner commandoFromServer = new Scanner(socket.getInputStream());
        Integer i = Integer.parseInt(commandoFromServer.nextLine());
        return i;
    }
    /**
     * Gets a String response from the server. This method i used to create other users and give them the correct username.
     * 
     * @param i
     * @return
     * @throws IOException
     */
    public String getStringResponse(int i) throws IOException {
        pw.print(i);
        pw.flush();
        Scanner commandFromServer = new Scanner(socket.getInputStream());
        String x = commandFromServer.nextLine();
        return x;

    }


}

除此之外我还有一个用作“主要”类的GUI。

我有一个名为SocketTest v3.0.0的程序(如果有人知道的话)它基本上做的是它为我创建了一个可以连接的服务器。

现在我的程序运行并连接到服务器!但是当我尝试在我的客户端程序中调用方法sendCommand或sendChat或任何其他方法(除了连接)之后,它给了我一个nullpointer execption。

我已经将问题缩小到当我声明套接字然后套接字为null时如何解决这个问题?因为我无法在我的Public类下初始化套接字!

我希望你明白我的意思,如果没有请回复,我会详细介绍!

提前谢谢!

3 个答案:

答案 0 :(得分:1)

似乎很奇怪“sendCommandO”创建了自己的printwriter而不是使用 全球性的。以后有两个打印机正在喂食,这肯定是在麻烦 相同的流。 “连接”立即发送“连接......”似乎很奇怪。

这个程序的结构通常不会起作用,因为在读者阅读之前,你的写作会阻塞并且无法解锁。它似乎适用于少量数据。读写必须在不同的线程中完成。

这些都不是你当前的问题,但我建议完全改写。

答案 1 :(得分:1)

在插座的使用寿命期间,您必须使用相同的流,扫描仪等。每次要进行I / O时都不会创建新的。否则,您将丢失缓冲区中的数据。

答案 2 :(得分:0)

首先,谢谢你们所有的帮助和回应,这就是我的代码工作的原因:

  1. 清除代码以确保每个代码中只有1个已创建,并且这些代码是在客户端连接到服务器时创建的

  2. 为了确保我可以在所有方法中同时使用PrintWriter和Scanner,我必须将字段设为静态

  3. 感谢您的帮助,我的客户端现在连接到服务器,并能够反复发送消息! :)

    完整的代码来到这里:

        import java.io.IOException;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.util.Scanner;
    
    
    public class Client {
    
        public final static int portNumber = 6040;
        public static Socket socket;
        private static PrintWriter pw;
        private static Scanner input;
        /**
         * @param args
         * @throws IOException 
         */
        public static void connect() throws IOException{
    
    
            // du kan vælge at bruge inetadressen til at connecte i socketet.
            InetAddress adr = InetAddress.getByName("localhost");
            socket = new Socket("localhost", portNumber);
            input=new Scanner(socket.getInputStream());
            pw = new PrintWriter(socket.getOutputStream());
            pw.println("Connected waiting for input");
            pw.flush();
    
        }
        /**
         * This method sends the message (that the client(chat person) writes to the user)
         * @param x
         * @throws NullPointerException
         * @throws IOException 
         */
        public void SendChat(String x) throws NullPointerException{
                pw.print(x);
                pw.flush(); 
    
    
        }
        public int sendCommando(int id) throws IOException{
            pw.print(id);
            pw.flush();
            /*
             * this part of the program sends a command to the server if the command is 1 then 1 is = Connect.
             * the program then ask the server is the server is full or is it ok to connect? 
             * if the response is not 10 then the program will allow a connection to happen the return type will be the Id of which 
             * the chat person becomes!
             */
    
            // should the method return 0 the Application will do NOTHING!
            switch (id) {
            case 1:
        int k = reciveCommando();
                if (k== 10) {
                    return 10;
                }else if (k < 3) {
                    System.out.println("returned k" + k);
                    return k;
                }else {
    
                return 10;
                }
                /*
                 * Closes the connection with the server!
                 */
            case 3:
    
                socket.close();
                return 0;
    
            default:
                return 0;
            }
    
        }
        /*
         * this method recives a command from the server! the comands can be found in the ChatCommands.txt
         * returns the command as an integer!
         */
        public int reciveCommando() throws IOException{
            Integer i = input.nextInt();
            return i;
        }
        /**
         * Gets a String response from the server. This method i used to create other users and give them the correct username.
         * 
         * @param i
         * @return
         * @throws IOException
         */
        public String getStringResponse(int i) throws IOException {
            pw.print(i);
            pw.flush();
            String x = input.nextLine();
            return x;
    
        }
    
    
    }