简体   繁体   中英

java calling method outputs nothing

I have a method which takes an IP, receives data and stores it in a List. At the end of the method it returns this List. However when this method is called, the list is empty. I think it is a really simple fix and it's me being stupid but could anyone point me to where I have gone wrong so I dont do it again?

public List<String> receiveDataFromOperator(){
    List<String> dataRec = new ArrayList<String>();

    try
    {

        System.out.println("Client Program");

        //Hard coded IP Address
        String ip = "146.176.226.147";

        //Hard coded port
        int port = 500;
        // Connect to the server
        Socket sock = new Socket(ip, port);

        // Create the incoming stream to read messages from
        DataInputStream network = new DataInputStream(sock.getInputStream());

        // Display our address
        System.out.println("Address: " + sock.getInetAddress());
        String line;

        // Loop until the connection closes, reading from the network
        while ((line = network.readUTF()) != null)
        {
            dataRec.add(line);


        }

        sock.close();
    }
    catch (IOException ioe)
    {


        //Test output for the arraylist size
        System.out.println(dataRec.size());


        for(int i = 0; i<dataRec.size(); i++){
            System.out.println("Line " + i + dataRec.get(i) + "\n");

        }



    }// End of catch

    return dataRec;

}//End of method

If the server is writing binary data with DataOutputStream.writeUTF() it should work.

If you are sending text from the server you need to read text from the socket with BufferedReader.readLine() .

BTW: When you get an IOException you generally shouldn't ignore it and pretend it didn't happen esp. when the program is not behaving as you expect.

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