Cri*_*ris -3 python tcp file send
我已经在网上寻找了如何在python中发送文件的每个地方,但100%失败了,没人能帮上忙。是否有程序员可以帮助我将文件从客户端发送到服务器或以其他方式发送?
我可以很容易地发送txt
#!/usr/bin/python
"""
Socket Client
"""
import socket #networking library
indent = ""
server = input("server name (default is " + socket.gethostname() + "): ") or socket.gethostname()
print("connecting to server at: %s" % server)
while True:
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect((server, 23000))
str = input("text to send: ")
clientSocket.send(str.encode("utf-8")) #send text as encoded bytes
print("received: %s" % clientSocket.recv(100).decode("utf-8"))
clientSocket.close()
#strRecv = clientSocket.recv(500).decode("utf-8") #receive up to 500 bytes and decode into text
#print(strRecv)
Run Code Online (Sandbox Code Playgroud)
很基本的例子:
import socket
with socket.socket() as s:
s.bind(('',8000))
s.listen(1)
with s.accept()[0] as c:
chunks = []
while True:
chunk = c.recv(4096)
if not chunk: break
chunks.append(chunk)
with open('out.txt','wb') as f:
f.write(b''.join(chunks))
Run Code Online (Sandbox Code Playgroud)
import socket
with socket.socket() as s:
s.connect(('localhost',8000))
with open('myfile.txt','rb') as f:
s.sendall(f.read())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3197 次 |
| 最近记录: |