简体   繁体   English

从套接字读取时获取空字符串

[英]Getting Null String when reading from a socket

I am trying to write a client-server system using Sockets in java, however I cannot seem to read data sent from the server to the client. 我正在尝试使用Java中的套接字编写客户端-服务器系统,但是我似乎无法读取从服务器发送到客户端的数据。

Here is the code for the client: 这是客户端的代码:

public class ClientSocket 
{
    Socket clientSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;


    // establish a connection to All Care's server application through socket 4444 (adjust localhost to reflect the IP address that the server
    // is being run from)
    public ClientSocket()
    {
        try
        {
            clientSocket = new Socket("localhost", 4445);

            out = new PrintWriter(clientSocket.getOutputStream());
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        }
        catch (IOException e)
        {
            System.out.println("Could not connect to All Care Server Application");
        }
    }

    public void closeClientSocket()
    {   
        try
        {
            clientSocket.close();
        }
        catch (IOException e)
        {
            System.out.println("Could not close connection to All Care Server Application");
        }
    }

    public String getMessageFromServer()
    {
        try
        {
            String input = in.readLine();

            return input;
        }
        catch (IOException e)
        {
            System.out.println("Could not read message from server");
        }

        return "No Data";
    }

    public void sendMessageToServer(String message)
    {
        out.write(message);
    }
}

And here is the Server code: 这是服务器代码:

public class ArFileServer {

    public static void main(String[] args) 
    {
        ServerSocket serverSocket = null;
        boolean listening = true;

        try
        {
            serverSocket = new ServerSocket(4445);

            // infinite loop to continually listen for connection requests made by clients
            while (listening)
            {
                new ClientConnection(serverSocket.accept()).start();

                if (serverSocket != null)
                {
                    System.out.println("Connection to client established");
                }
            }

            serverSocket.close();
        }
        catch (IOException e)
        {
            System.out.println("Error could not create socket connection to port");
        }
    }
}

public class ClientConnection extends Thread
{
    private Socket socket = null;

    public ClientConnection(Socket socket) 
    {
        super("ClientConnection");
        this.socket = socket; 
    }

    // the thread that runs after a connection to the server has been accepted
    @Override
    public void run()
    {
        try
        {
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            sendMessagetoClient(out, "CONNECTION SUCCESS");

            // check login credentials sent from client to the server

            // if valid send back their encrypted password, otherwise output a login error message

            // wait for user input and then do various processes based on their requests

            in.close();
            out.close();
            socket.close();
        }
        catch (IOException e)
        {
            System.out.println("Client socket connection error");
        }
    }

    // sends a message to the client
    void sendMessagetoClient(PrintWriter out, String message)
    {
        out.write(message);
    } 

    // listens for a message from the client
    String getMessageFromClient(BufferedReader in)
    {      
        try
        {
            String input = in.readLine();
            return input;
        }
        catch (IOException e)
        {
            System.out.println("Could not read message from client");
        }

        return "No Data";
    }

And here is the line of code im using to see if the data is being sent. 这是im用于查看数据是否正在发送的代码行。

System.out.println(clientSocket.getMessageFromServer());

In your sendMessageToClient() method, you need to flush: sendMessageToClient()方法中,您需要刷新:

void sendMessagetoClient(PrintWriter out, String message)
{
    out.write(message);
    out.flush();
} 

Or, when you create the PrintWriter , use the constructor with autoflush : 或者,在创建PrintWriter ,将构造函数与autoflush一起autoflush

PrintWriter out = new PrintWriter(socket.getOutputStream(),true);

And when you write, instead of out.write(message) use printf() or println() . 并且在编写时,请使用printf()println()代替out.write(message) println()

There are several problems here. 这里有几个问题。

  1. You are reading lines but you aren't writing lines. 您正在阅读台词,但没有在写台词。

  2. You aren't checking the result of readLine() for null, which means the peer has closed the connection, which means you must do likewise. 您没有检查readLine()的结果是否为null,这意味着对等方已关闭连接,这意味着您必须这样做。

  3. You aren't flushing the PrintWriter after you write. 编写后,您无需刷新PrintWriter

  4. You are closing things in the wrong order. 您以错误的顺序关闭事物。 You must close the output writer/stream you have attached to the socket. 您必须关闭已附加到套接字的输出编写器/流。 Doing that flushes it and then closes the input stream/reader and the socket. 这样做会冲洗它,然后关闭输入流/阅读器和套接字。 Doing this in the wrong order loses the flush. 以错误的顺序执行此操作会丢失刷新。 Once you've closed the output you don't need the other two closes. 关闭输出后,就不需要另外两个关闭。

  5. You are using PrintWriter, which swallows exceptions, across a network, where you need to know about exceptions and errors in communication, and you aren't checking for errors either. 您正在使用PrintWriter,它将通过网络吞下异常,您需要在该网络中了解通信中的异常和错误,而且也不会检查错误。 Use a BufferedWriter. 使用BufferedWriter.

in the clint code you are not connecting with server socket. 在clint代码中,您未与服务器套接字连接。 for clint socket connection 用于克林特插座连接

socket soc= new socket ("server host ip",port);

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

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