我正在尝试在客户端和服务器之间发送一些号码。在关闭服务器之前,我发送字符串“End”。客户端检查它正在读取的字符串是否为“End”。如果不是,它将捕获该字符串。但是,我面临两个问题。 首先,我发送了 7 个号码,但由于某种原因,收到了 4 个号码(每隔一个号码)。例如,我从服务器发送这些号码:[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 block 内调用 readObject,使其读取两次。
另外,不要将字符串与 == 进行比较,而是使用 equals,因为结果返回 false,您的 while 循环将在 EOFException 上的关闭结果后尝试读取更多内容。
使用您已经读过一次的变量“test”
while(!(test = (String) ois.readObject()).equals("End")) {
System.out.println(test);
Object n1 = test;
关于java - 检测服务器套接字关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51563386/