Reputation: 1166
Probably a simple question for those who used to play with socket
module. But I didn't get to understand so far why I can't send a simple file.
As far as I know there are four important steps when we send an info over a socket:
Now, what I want to do is creating a file on my local machine and fill it with some info. ( been there, done that - all good so far )
Then, I create my client flow, which is the following:
s = socket.socket() # create a socket
s.connect(("localhost", 8081)) # trying to connect to connect over 8081 port
f = open("logs.txt", "rb+") # I'm opening the file that contains what I want
l = f.read(1024) # I'm reading that file
# I'm sending all the info from the file
while l:
s.send(l)
l = f.read(1024)
s.close()
Of course, firstly, I'm creating a server (at first, on my localhost) which will open that port and basically create the connection which will allow the byte-chunked data to be sent.
import socket
import sys
s = socket.socket() # create the 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 to open a new file on the server ( which in this case is also my localhost )
while True: # write all the data to the file and close everything
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, what doesn't work on my Ubuntu 14.10 machine:
python server.py
after the client script finishes writing some data in logs.txt
and connects to the server, I get the following response on the server:
<socket._socketobject object at 0x7fcdb3cf4750> ('127.0.0.1', 56821)
What am I doing wrong ? The port is also different from the one that I set ( I also know that the port is not used - verifiet with nc
).
Can anybody explain me how to correctly treat this problem ?
Upvotes: 0
Views: 614
Reputation: 6777
I'm not sure what your second while True
loop is for. Remove that, and it works as you expect:
import socket
import sys
s = socket.socket() # create the 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()
Upvotes: 2