我创建了一个相当简单的服务器,目的是发送一个简单的.txt文件,但由于某种原因它不会发送。
服务器代码:
import socket
port = 8081
host = "192.168.0.20"
s = socket.socket()
s.bind((host, port))
s.listen(5)
print("Server Listening.....")
while True:
conn, addr = s.accept()
print("Got connection from", addr)
data = conn.recv(1024)
print("Data recieved", repr(data))
filename = "/Users/dylanrichards/Desktop/keysyms.txt"
f = open(filename, 'rb')
l = f.read(1024)
while (l):
conn.send(l)
print("Sent", repr(l))
l = f.read(1024)
f.close()
print("Done sending")
conn.send("Thank you for connecting")
conn.close()
以下是客户端的代码:
import socket
port = 8081
host = "192.168.0.20"
s = socket.socket()
s.connect((host, port))
with open("Recieved_File", 'wb') as f:
print("File opened")
while True:
print("Receiving data...")
data = s.recv(1024)
print("Data=%s", (data))
if not data:
break
f = open("/Users/dylanrichards/Desktop/test12.txt")
f.write(data)
f.close()
print("Successfully got file")
print("Connection closed")
s.close()
我在Macbook Air上通过我的本地网络进行测试,如果有任何帮助的话。提前谢谢......
答案 0 :(得分:1)
f
with open("Recieved_File", 'wb') as f:
- 我认为这不是必需的。f = open("/Users/dylanrichards/Desktop/test12.txt")
应该在while
循环之外。客户代码:
import socket
port = 8081
host = "192.168.0.20"
s = socket.socket()
s.connect((host, port))
f = open("/Users/dylanrichards/Desktop/test12.txt",'wb')
while True:
print("Receiving data...")
data = s.recv(1024)
if not data:
break
print("Data=%s", (data))
f.write(data)
f.close()
print("Successfully got file")
print("Connection closed")
s.close()