本帖最后由 张少威 于 2012-6-2 22:55 编辑
我不知道是不是我的思路有问题。目的是客户端从服务器端下载到某文件。服务器端ServerSocket启动后,客户端建立socket,客户端向流中写入消息类型,需要的文件名等等,然后从流中逐个字节开始读文件的字节(我认为这时流中没有东西客户端程序会暂时阻塞在这),服务器端识别出消息类型,将需要的文件逐个字节写入流。
大概的代码如下
客户端- public void downloadFile(String groupName, String filePath, String fileName) {
- try {
- Socket socket = new Socket(serverIP, filePort);
- InputStream is = socket.getInputStream();
- ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
- oos.writeObject(new Integer(ClientToServerMessageType.DownloadFile));
- oos.writeObject(new String(account));
- oos.writeObject(new String(groupName));
- oos.writeObject(new String(fileName));
- oos.writeObject(new Long(0));
- oos.flush();
- File file = new File(filePath + fileName);
- FileOutputStream dos = new FileOutputStream(file);
- int temp;
- do {
- temp = ois.read();
- dos.write(temp); //问题就在这,我发现卡在这个循环中,不能跳出,我认为服务器端将-1写进去了的,应该能跳出
- }while(temp != -1);
- dos.flush();
- oos.close();
- dos.close();
- is.close();
- JOptionPane.showMessageDialog(null, "文件下载成功");
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (UnknownHostException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
复制代码 服务器端- //前面的那些account,groupName等已经从流中无误地读出来了,这是向流中写文件的数据
- private void provideFile(String groupName, String fileName, ObjectOutputStream oos) {
- File file = new File(ServerFileSavePath.fileSavePath + "\\" + groupName + "\\" + fileName);
- FileInputStream dis;
- try {
- dis = new FileInputStream(file);
- int temp;
- do {
- temp = dis.read();
- oos.write(temp);
- }while(temp != -1);
- oos.flush();
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
复制代码 |
|