[英]Detecting Server Socket Closing
我正在嘗試在客戶端和服務器之間發送一些號碼。 關閉服務器之前,我要發送字符串“ End”。 客戶端檢查正在讀取的字符串是否為“ End”。 如果否,它將捕獲字符串。 但是,我面臨着兩個問題。 首先,我發送了7個號碼,但由於某種原因,我得到了四個號碼(每個其他號碼)。 例如,我從服務器[79、20、42、0、10、31、21]發送這些數字,並在客戶端中獲得這些數字:[79、42、10、21]。 其次,即使正在檢查對象,我也會收到EOFException。
服務器代碼如下:
public class main {
public static void main(String[] args) throws IOException {
// Create a Socket
int port = 6000;
@SuppressWarnings("resource")
ServerSocket sersock = new ServerSocket(port);
Socket sock = sersock.accept( );
OutputStream ostream = sock.getOutputStream();
ObjectOutputStream pwrite = new ObjectOutputStream(ostream);
int q = 7;
SecureRandom rand = new SecureRandom();
int[] list = new int [q];
for (int i = 0; i < q; i++)
{
int num = rand.nextInt(100);
list[i] = num;
String n1 = Integer.toString(num);
pwrite.writeObject(n1);
}
System.out.println(Arrays.toString(list));
// Close the socket
pwrite.writeObject("End");
sock.close();
}
}
客戶端代碼如下:
public class main {
public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException {
// Create Socket
int port = 6000;
Socket sock = new Socket("localhost", port);
ObjectInputStream ois = new ObjectInputStream(sock.getInputStream());
String test = "";
ArrayList<String> numlist = new ArrayList<String>();
//while(! sock.isClosed())
while((test = (String) ois.readObject()) != "End")
{
System.out.println(test);
Object n1 = ois.readObject();
if(n1 instanceof String)
{
String n2 = (String) n1;
numlist.add(n2);
}
}
System.out.println("The collected clues are: ");
System.out.println(numlist);
}
}
您在while語句和while塊內部調用readObject,使其讀取兩次。
另外,請勿將字符串與==進行比較,而應使用equals代替,因為結果返回false,您的while循環將在EOFException的閉合結果后嘗試讀取更多內容。
使用您已經讀過一次的變量“ test”
while(!(test = (String) ois.readObject()).equals("End")) {
System.out.println(test);
Object n1 = test;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.