Server socket file transfer

我是研究僧i 提交于 2019-12-04 13:32:16

Yes, simply transfer the metadata (in your case myFile.getName()) before the actual file contents, and make client and server read and emit that metadata. It's a good idea to use established protocols, for example HTTP and its Content-Disposition header.

Peter Lawrey

For the receiver to know the file name, either:

a) it must assume it knows the name because it asked for it,

b) the server sends the name first as part of the stream.

If you invent a way to send information without actually sending it, let me know and we can become billionaires. We can call it 'computer telepathy'.

There is a simpler way to do this. Just wrap your input stream inside DataInputStream and use methods like .writeUTF(myFile.getName()). Similarly, you can read file name at receiver by applying .readUTF on DataInputStream. Here is a sample code: Sender:

FileInputStream fis = new FileInputStream(myFile);  
    BufferedInputStream bis = new BufferedInputStream(fis);
    DataInputStream dis = new DataInputStream(bis);
    OutputStream os;
    try {
        os = socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeUTF(myFile.getName());  
.............////// catch exceptions

Receiver:

InputStream in;
    try {
        bufferSize=socket.getReceiveBufferSize();
        in=socket.getInputStream();
        DataInputStream clientData = new DataInputStream(in);
        String fileName = clientData.readUTF();
        System.out.println(fileName);
................../////// catch exceptions
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!