[英]socket programming client freezing python
基本上,我有一個 python 客戶端發送命令要求服務器做一些事情,我已經實現了線程,但它似乎不起作用。 例如,當我向服務器發送“啟動”命令時,它會執行job_function,但在此期間,客戶端凍結。 所以基本上,我希望我的服務器在執行任務時仍然能夠響應客戶端的請求,這就是我使用線程的原因。
服務器.py:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 5005)) # Bind to the port
s.listen(1) # Now wait for client connection.
c, addr = s.accept() # Establish connection with client.
while True:
print('Got connection from', addr)
data = c.recv(1024).decode()
print(data)
if data == "start":
print("start the service")
c.sendall('started service'.encode())
threading.Thread(target=job_function).start()
elif data == "suspend":
print("suspend service")
c.sendall('suspended service'.encode())
else:
c.sendall('wrong command'.encode())
c.close() # Close the connection
客戶端.py:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',5005))
while True:
x = input("Enter command: ")
s.sendall(x.encode())
print(x)
data = s.recv(1024).decode()
print(data)
s.close()
也可以僅使用 recv() 函數來完成。
客戶端:
sssize = os.stat('fileName').st_size
file = open('fileName', 'rb')
amm = file.read(sssize)
dfd = amm
#########
c.send(bytes(str(sssize), 'utf-8'))
rrespo = c.recv(1024).decode()
######
if rrespo == 'yess':
m = 0
lenmsg = 1024
loop = (int((sssize) / lenmsg))
if (sssize)<lenmsg:
c.send(dfd[0:sssize])
else:
dddf='oksend'
for ioo in range(0, loop):
if dddf=='oksend':
c.send(dfd[ioo * lenmsg:ioo * lenmsg + lenmsg])
stloop = ioo * lenmsg + lenmsg
print(int(m / (loop - 1) * 100))
m = m + 1
dddf = c.recv(6).decode()
print(dddf, ioo)
nextloop = sssize - loop * lenmsg
if nextloop > 0:
c.send(dfd[stloop:stloop + nextloop])
file.close()
print('file transffered successfully')
服務器端:
filename = input(str("Enter file name :")
fill = open(filename, 'wb')
c.send(bytes(commm, 'utf-8'))
# sizze=c.recv(1024).decode()
# print('size')
# print(sizze)
# c.send(bytes('done', 'utf-8'))
fileSize = c.recv(1024).decode()
c.send(bytes('yess', 'utf-8'))
lenmsg=1024
loop = int(int(fileSize) / lenmsg)
if (int(fileSize))<lenmsg:
image = c.recv(int(fileSize))
fill.write(image)
else:
for i in range(0, loop):
image = c.recv(lenmsg)
fill.write(image)
print('completed downloading:', int((i / (loop - 1) * 100)), '%')
c.send(bytes('oksend', 'utf-8'))
nextloop = int(fileSize) - loop * lenmsg
if nextloop > 0:
image = c.recv(nextloop)
fill.write(image)
fill.close()
print('file downloaded successfully')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.