简体   繁体   English

套接字未连接

[英]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. 除此之外,我有一个GUI,我用作我的“主要”类。

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. 我有一个名为SocketTest v3.0.0的程序(如果你们其中任何人都知道的话)它基本上做的是它为我创建了一个可以连接的服务器。

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. 但是当我尝试在我的客户端程序(除了连接)中调用方法sendCommand或sendChat或任何其他方法之后,它给了我一个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? 我已经缩小了问题,当我声明套接字然后套接字是null我怎么能解决这个问题? because i am unable to initilize the socket under my Public class! 因为我无法在我的Public类下初始化套接字!

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. 似乎很奇怪“sendCommandO”创建了自己的printwriter而不是使用全局的printwriter。 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. 每次要进行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 为了确保我可以在我的所有方法中使用PrintWriter和Scanner,我必须使字段为静态

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;

    }


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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