Java 无法将数据输入到dataoutputstream
我正在创建一个程序,从文件中读取数据,然后将其更改为项目的arraylist,并将其发送到客户端。客户根据id选择项目并输入所需金额。然后它在服务器中得到更新。服务器运行多线程。当另一个客户机调用服务器时,更新的金额将提供给该客户机 我对客户端的代码有问题。发生的情况是我无法输入id和金额,因为程序在我输入值之前关闭Java 无法将数据输入到dataoutputstream,java,sockets,datainputstream,dataoutputstream,Java,Sockets,Datainputstream,Dataoutputstream,我正在创建一个程序,从文件中读取数据,然后将其更改为项目的arraylist,并将其发送到客户端。客户根据id选择项目并输入所需金额。然后它在服务器中得到更新。服务器运行多线程。当另一个客户机调用服务器时,更新的金额将提供给该客户机 我对客户端的代码有问题。发生的情况是我无法输入id和金额,因为程序在我输入值之前关闭 public class ListClient { public static void main(String[] args) throws ClassNotFoundExce
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
}
是因为pickItem中返回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;
}
请参见此处的第一个示例:
如果要查询用户输入,则必须从System.in读取数据,并使用扫描仪或类似设备进行读取
像这样
Scanner fromUser = new Scanner(System.in);
try (DataOutputStream dos = new DataOutputStream(s1.getOutputStream())) {
System.out.println("Enter the item id that you want:\n");
id = fromUser.nextInt();
dos.writeInt(id);
System.out.println("Enter the amount of item that you want:\n");
amt = fromUser.nextInt();
dos.writeInt(amt);
dos.flush();
}
当然,有更多的方法可以实现同样的目标。这只是一个…不要在同一个套接字上混合不同类型的流。在两端对所有内容使用ObjectInputStream和ObjectOutputStream。他们有你需要的所有方法。如果混用,您将遇到缓冲问题,其中一个从另一个窃取数据。您在console中是否遇到任何异常?您不会从console读取数据,是吗?客户端中没有使用扫描仪或System.in…@BlackPanther请参阅@Fildor:thx以获取链接匹配…:
Scanner fromUser = new Scanner(System.in);
try (DataOutputStream dos = new DataOutputStream(s1.getOutputStream())) {
System.out.println("Enter the item id that you want:\n");
id = fromUser.nextInt();
dos.writeInt(id);
System.out.println("Enter the amount of item that you want:\n");
amt = fromUser.nextInt();
dos.writeInt(amt);
dos.flush();
}