简体   繁体   中英

Request File from server using sockets

I am creating a program where an android device requests a file from a Web Server(running python).The server can receive over sockets with no problem the path of the requested file but i dont know how i can make my android device to wait for a responce.

Here is the android code(as a client requesting a file from web server):

 try {

        Socket socket = null;
        socket = new Socket("192.168.1.9", 4000);

        DataInputStream input = new DataInputStream(socket.getInputStream());
        DataOutputStream output = new DataOutputStream(socket.getOutputStream());


        String str = getURL();
        output.writeBytes(str);

        output.close();
        input.close();
        socket.close();

        {
        }
    } catch (IOException e) {
    }


    Log.d("communicationService", "URL transferred with success");

And the python script running on Web Server(It can receive thefile path but i have problem sending the file)

import socket
import sys

HOST, PORT = '192.168.1.9', 4000
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serverSocket.bind((HOST,PORT))
serverSocket.listen(10)

print 'Server is on and listening to %s ... ' % PORT

while True:

clientSocket, clientAddress = serverSocket.accept()
print 'A client was connected.....'
incomingURL = clientSocket.recv(1024)
print incomingURL

clientSocket.close()

Any advice and tip would be really helpful...

I imagine you should be able to get away with SimpleHTTPServer

If you need to get fancier with a full blown webservice, WSGI is very popular.

On the client side Requests library is by far the easiest way that I've found to make http requests in python. (just had to plug that one because it's that good)

Well i managed to transfer the files in the end(For those that are interested in apps of this kind).What i did was to create another socket and sent a stream back to client.

file = open("path_of_file", "rb")

s = socket.socket()
s = connect((addr,port))
l = file.read(1024)
while (l):
  s.send(l) 
  l.f.read(1024)
file.close()
s.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM