我有一个方法,它需要一个 IP,接收数据并将其存储在一个列表中。在方法结束时,它返回此列表。但是,当调用此方法时,列表为空。我认为这是一个非常简单的解决方法,而且我很愚蠢,但是有人能指出我哪里出错了,所以我不再这样做了吗?
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