sockets - Sending a file from local to server using python - the correct way -
probably simple question used play socket
module. didn't understand far why can't send simple file.
as far know there 4 important steps when send info on socket:
- open socket
- bind
- listen
- accept ( possibly needed multiple times ).
now, want creating file on local machine , fill info. ( been there, done - far )
then, create client flow, following:
s = socket.socket() # create socket s.connect(("localhost", 8081)) # trying connect connect on 8081 port f = open("logs.txt", "rb+") # i'm opening file contains want l = f.read(1024) # i'm reading file # i'm sending info file while l: s.send(l) l = f.read(1024) s.close()
of course, firstly, i'm creating server (at first, on localhost) open port , create connection allow byte-chunked data sent.
import socket import sys s = socket.socket() # create socket s.bind(("localhost", 8081)) # bind s.listen(10) while true: sc, address = s.accept() print sc, address f = open('logs_1.txt', 'wb+') # trying open new file on server ( in case localhost ) while true: # write data file , close l = sc.recv(1024) f.write(l) l = sc.recv(1024) while l: f.write(l) l = sc.recv(1024) f.close() sc.close() s.close()
now, doesn't work on ubuntu 14.10 machine:
- the server part runs without error when doing
python server.py
after client script finishes writing data in
logs.txt
, connects server, following response on server:<socket._socketobject object @ 0x7fcdb3cf4750> ('127.0.0.1', 56821)
what doing wrong ? port different 1 set ( know port not used - verifiet nc
).
can explain me how correctly treat problem ?
i'm not sure second while true
loop for. remove that, , works expect:
import socket import sys s = socket.socket() # create socket s.bind(("localhost", 8081)) # bind s.listen(10) while true: sc, address = s.accept() print sc, address f = open('logs_1.txt', 'wb+') l = sc.recv(1024) while l: f.write(l) l = sc.recv(1024) f.close() sc.close() s.close()
Comments
Post a Comment