我正在创建一个从文件读取的程序,然后将其更改为项目的数组列表并将其发送给客户端。客户通过 id 选择一个项目并输入所需的金额。然后它会在服务器中更新。服务器运行多线程。当另一个客户端调用服务器时,更新的金额将提供给客户端。
我在客户端的代码有问题。发生的事情是我无法输入 id 和 amt,因为程序在我输入值之前关闭。
public class ListClient {
public static void main(String[] args) throws ClassNotFoundException, IOException {
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
int id = 0;
int amt = 0;
Socket s1 = new Socket("localhost", 2001);
ois = new ObjectInputStream((s1.getInputStream()));
System.out.println("Connected to test server");
ListFacade2 lf = new ListFacade2();
List<Item> lm = (ArrayList<Item>) ois.readObject();
lf.setItemList(lm);
Item it = lf.pickItem();
System.out.println("Item " + it.getId() + " Amount " + it.getQty_left());
if(it.getQty_left()>0){
try (DataOutputStream dos = new DataOutputStream(s1.getOutputStream())) {
System.out.println("Enter the item id that you want:\n");
dos.writeInt(id);
System.out.println("Enter the amount of item that you want:\n");
dos.writeInt(amt);
dos.flush();
}}
else
System.out.println("Item out of stock");
} finally {
try {
if (ois != null) {
ois.close();
}
if (oos != null) {
oos.close();
}
} catch (IOException ex) {
}
}
} // end main
}
这是来自服务器端的代码
public class ListServer {
public static void main(String[] args) {
try {
ServerSocket sSoc1 = new ServerSocket(2001);
while (true) {
Socket inSoc1 = sSoc1.accept();
ListThread lt = new ListThread(inSoc1);
lt.start();
}
} catch (Exception e) {
System.out.println("Oh Dear! " + e.toString());
}
}
}
class ListThread extends Thread {
Socket threadSoc1;
ListFacade lf = new ListFacade();
ListThread(Socket inSoc1) throws IOException, ClassNotFoundException {
threadSoc1 = inSoc1;
lf.readItemList();
}
@Override
public void run() {
try {
ObjectOutputStream oos = new ObjectOutputStream((threadSoc1.getOutputStream()));
System.out.println("server Soc1ket runs");
oos.writeObject(lf.getListItem());
DataInputStream dis = new DataInputStream(threadSoc1.getInputStream());
int id = dis.readInt();
int amt = dis.readInt();
lf.updateItem(id, amt);
lf.displayItem();
} catch (Exception e) {
System.out.println("Whoops! " + e.toString());
}
try {
threadSoc1.close();
} catch (Exception e) {
System.out.println("Oh no! " + e.toString());
}
}
}
是因为 pickItem() 中的 return null 吗?
public Item pickItem() throws IOException, ClassNotFoundException {
displayItem();
System.out.print("Please Key in item id number from above list: ");
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
Integer itno = Integer.parseInt(b.readLine());
for(int i = 0; i < im.size();i++){
if(im.get(i).id.equals(itno))
return im.get(i);
else
System.out.println("No such item");
}
return null;
}