![](/img/trans.png)
[英]Sending an Image from Client to Server using Sockets in Python
[英]Sending Txt file to server from client using python sockets
我正在尝试使用套接字在python中创建服务器/客户端来发送文本和其他媒体文件。 场景:-客户端将主机,端口和文件名作为参数,并将文件发送到服务器。 错误描述:-试图执行以下客户端代码时,文本文件“ tos”与client在同一目录中。
**$ python Cli.py 127.0.0.1 5007 tos**
Traceback (most recent call last):
File "Cli.py", line 32, in <module>
client= Client(host,port,file)
File "Cli.py", line 15, in __init__
self.connect(file)
File "Cli.py", line 20, in connect
self.sendFile(file)
File "Cli.py", line 26, in sendFile
readByte = open(file, "rb")
**IOError: [Errno 2] No such file or directory: ''**
注意:-还请说明是否仍然有文件要发送到服务器,请搜索硬盘驱动器。
服务器:-
from socket import *
port = 5007
file = ''
class Server:
gate = socket(AF_INET, SOCK_STREAM)
host = '127.0.0.1'
def __init__(self, port):
self.port = port
self.gate.bind((self.host, self.port))
self.listen()
def listen(self):
self.gate.listen(10)
while True:
print("Listening for connections, on PORT: ", self.port)
add = self.gate.accept()
self.reciveFileName()
self.reciveFile()
def reciveFileName(self):
while True:
data = self.gate.recv(1024)
self.file = data
def reciveFile(self):
createFile = open("new_"+self.file, "wb")
while True:
data = self.gate.recv(1024)
createFile.write(data)
createFile.close()
server= Server(port)
listen()
客户:-
#!/usr/bin/env python
from socket import *
host = ''
port = 5007
file = ''
class Client:
gateway = socket(AF_INET, SOCK_STREAM)
def __init__(self, host,port, file):
self.port = port
self.host = host
self.file = file
self.connect()
def connect(self):
self.gateway.connect((self.host, self.port))
self.sendFileName(file)
self.sendFile(file)
def sendFileName(self):
self.gateway.send("name:" +self.file)
def sendFile(self):
readByte = open(self.file, "rb")
data = readByte.read()
readByte.close()
self.gateway.send(data)
self.gateway.close()
client= Client(host,port,file)
connect()
目前, file = ''
这不是有效的文件名。 为了清楚起见,我还建议将file
重命名为filename
。
3个月前以家庭作业的形式完成了这项任务。 解决方案非常简单-您只需要读取文件,将读取的文本放入字符串变量中并发送即可。 查看以下服务器代码:
HOST = '192.168.1.100'
PORT = 8012
BUFSIZE = 1024
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind(ADDR)
serversock.listen(SOMAXCONN)
fileOpen = open("D:/fileLocation.txt")
g = f.read()
print 'Waiting For Connection..'
clientsock, addr = serversock.accept()
print 'Connection Established From: ', addr`
clientsock.sendall(g)
这是一种非常简单的方法。
客户端仅接收数据(作为文本)并将其保存在所需位置。
还为我处理了BMP,PNG和JPG图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.