[英]Detecting Server Socket Closing
I am trying to send some numbers between client and server. 我正在尝试在客户端和服务器之间发送一些号码。 Before closing the server, I am sending the string "End".
关闭服务器之前,我要发送字符串“ End”。 The client checks if the string it is reading is "End" or not.
客户端检查正在读取的字符串是否为“ End”。 If no, it will capture the string.
如果否,它将捕获字符串。 However, I am facing two issues with it.
但是,我面临着两个问题。 First, I am sending 7 numbers but for some reason, getting four numbers (every other number).
首先,我发送了7个号码,但由于某种原因,我得到了四个号码(每个其他号码)。 For example, I am sending these numbers from server: [79, 20, 42, 0, 10, 31, 21] and getting these numbers in client: [79, 42, 10, 21].
例如,我从服务器[79、20、42、0、10、31、21]发送这些数字,并在客户端中获得这些数字:[79、42、10、21]。 Second, I am getting an EOFException, even though I am checking the object.
其次,即使正在检查对象,我也会收到EOFException。
The server code is below: 服务器代码如下:
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();
}
}
The client code is below: 客户端代码如下:
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);
}
}
You calling readObject inside the while statement and inside the while block, making it reading twice. 您在while语句和while块内部调用readObject,使其读取两次。
Also, don't compare Strings with == use equals instead, since the result returns false your while loop will try to read more after closed resultion on EOFException. 另外,请勿将字符串与==进行比较,而应使用equals代替,因为结果返回false,您的while循环将在EOFException的闭合结果后尝试读取更多内容。
Use the variable 'test' you already readed once 使用您已经读过一次的变量“ test”
while(!(test = (String) ois.readObject()).equals("End")) {
System.out.println(test);
Object n1 = test;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.