简体   繁体   中英

Socket not connected

my question is as follows: I have the following client class:

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;

    }


}

other than that i have a GUI that i use as my "main" class.

i have a program called SocketTest v3.0.0 (if any of you guys know it) what it basicly does is that it creates a server for me that i can connect to.

Now my program runs and connects to the server! But when i try to call the method sendCommand or sendChat or any other methodes in my Client program (besides connect) then it gives me a nullpointer execption.

I have narrowed the problem down to be that when i declare the socket then the socket is null how can i fix this? because i am unable to initilize the socket under my Public class!

I hope you understand what i mean and if not please respond and il go into more details!

Thank you in advance!

It seems curious that "sendCommandO" creates its own printwriter instead of using the global one. It's definitely asking for trouble later to have two printwriters feeding the same stream. It also seems odd that "connect" immediately sends "connected..."

This structure of this program will not work, in general, because your writing will block and be unable to unblock until the reader has read something. It will seem to work fine for small amounts of data. The reading and writing must be done in separate threads.

None of these is your immediate problem, but I suggest a complete rewrite.

You must use the same streams, scanners etc., for the life of the socket. Not create new ones every time you want to do I/O. Otherwise you will lose data in buffers.

First of all thank you guys for all of your help and responses this is what made my code work:

  1. Cleaned the code to make sure that only 1 of each were created and these were created when the client connects to the server

  2. in order to make sure that i could use both the PrintWriter and Scanner in all of my methods i had to make the fields Static

Thank you for all of your help my client now connects to the server and is able to send the messages back and forward! :)

the full code comes here:

    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;

    }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM