从套接字接收数据时脚本挂起

时间:2019-04-30 21:29:42

标签: python python-3.x socketserver

这是我的python脚本,用于从客户端接收数据:

import time
import socket

HOST = ''
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')

try:
    s.bind((HOST, PORT))
except socket.error as socketError:
    print('socket binding failed, ', socketError)
    print('Exiting...')
    sys.exit(0)

print('Socket binding complete')

s.listen(1)
print('Socket listening for connection...')

conn, addr = s.accept()

print('connected to ', addr[0])

bfr = b''
try:
    while True:
        while True:
            temp = conn.recv(1024)
            print('temp is ',temp.decode('utf-8'))
            print('buffer value ', bfr.decode('utf8'))
            if not temp:
                break
            bfr += temp;
        data = bfr.decode('utf-8')
        bfr = b''
        print('value received,', data)
        if data == 'Connection-Ready to receive commands':
            print('')
        #other conditions
except Exception as loopException:
    print("Exception occurred in loop, exiting...")
finally:
    s.close()

打印后脚本挂断 connected to 192.168.4.197 并且不接受来自客户端的任何命令。如果客户端断开连接,则将打印所有发送命令。

有人知道它为什么会这样吗?请询问您是否需要更多详细信息

更新1

尝试删除内部内容,并添加了time.sleep(.10),脚本未挂起,但只有第一个命令按原样打印,其余命令在第一个字符之后以换行符打印,例如,如果我发送10 ,它将首先打印1,在另一行打印0。我只想获取从客户端发送来的命令,每个命令都是单个单词。

1 个答案:

答案 0 :(得分:0)

也许尝试sendall以确保数据是从客户端完整发送的?