我尝试使用套接字将数据从MySQL
传递到客户端。对于List
,我更喜欢使用数组,但如果我使用这个发送数组:
InputStream input = client.getInputStream();
OutputStream output = client.getOutputStream();
ObjectOutputStream obOutput = new ObjectOutputStream(output);
Statement statement = dataConnection.createStatement();
ResultSet modList = statement.executeQuery("SELECT modID, downloads FROM modRegister");
String[][] mods = new String[3][3];
int column = 0;
while (modList.next()) {
mods[column][1] = modList.getString("modID");
mods[column][2] = modList.getString("downloads");
++column;
}
System.out.println(mods[1][1]);
PrintWriter printClient = new PrintWriter(output);
printClient.println(column);
printClient.close();
obOutput.writeObject(mods);
obOutput.flush();
并使用以下方式从客户端接收:
Socket server = new Socket("localhost", 25566);
InputStream input = server.getInputStream();
OutputStream output = server.getOutputStream();
ObjectInputStream obInput = new ObjectInputStream(input);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String s;
int columns = 0;
while((s = reader.readLine()) != null) {
columns = Integer.parseInt(s);
System.out.println(s);
}
String [][] mods;
TimeUnit.SECONDS.sleep(10);
mods = (String[][])obInput.readObject();
我得到EOFException
,即使有时间延迟。数组有效。我测试了打印出来的所有数据。这是一个例外:
Caused by: java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2601)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1319)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
at layout.MainStoreController.initialize(MainStoreController.java:36)
... 32 more
答案 0 :(得分:1)
我怀疑关闭PrintWriter会关闭它写入的OutputStream。
PrintWriter printClient = new PrintWriter(output);
printClient.println(column);
printClient.close();
当流关闭时,套接字关闭,另一端将在读取时观察文件结束。