微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python3.7中的套接字recv错误

如何解决python3.7中的套接字recv错误

客户:

#The program should send two strings and the server should return the interclassed string back

import socket
import time
import sys


HEADERSIZE=10
firstString = input("First string: ")
secondString = input("Second string: ")
host = "127.0.0.1"
port = 8888
firstString = f'{len(firstString):<{HEADERSIZE}}'+firstString
secondString = f'{len(secondString):<{HEADERSIZE}}'+secondString

s = socket.socket(socket.AF_INET,socket.soCK_STREAM)
s.connect((host,port))
s.send(bytes(firstString,'utf-8'))
s.send(bytes(secondString,'utf-8'))
fullMsg=''
while 1:
    msg = s.recv(8)
    if len(msg)<=0:
        break
    fullMsg += msg.decode('utf-8')
print(fullMsg)
s.close()

服务器:

#trebuie trimisa si dimensiunea
import socket


def interclass(firstString,secondString):
    i =0 
    j =0
    interString=''
    while i < len(firstString) and j < len(secondString):
        if firstString[i] < secondString[j]:
            interString+=firstString[i]
            i=i+1
        else: 
            interString+=secondString[j]
            j=j+1
    while i < len(firstString):
        interString += firstString[i]
        i=i+1
    while j < len(secondString):
        interString+=secondString[j]
        j=j+1
    return interString

host = "127.0.0.1"
port = 8888;
HEADERSIZE=10

s = socket.socket(socket.AF_INET,socket.soCK_STREAM)
s.bind((host,port))
s.listen(1)
while True:
    conn,addr = s.accept()
    messages=[]
    newMsg = True
    fullMsg = ''
    msgLength = -1
    while True:
        msg = conn.recv(16)
        if len(msg)<=0:
            break
        msg = msg.decode('utf-8')
        fullMsg += msg
        if len(fullMsg)>=HEADERSIZE and newMsg == True:
            newMsg = False
            msgLength = int(fullMsg[:HEADERSIZE-1])
            fullMsg = fullMsg[HEADERSIZE:HEADERSIZE+1+msgLength]
        if not newMsg and len(fullMsg)>=msgLength:
            messages.append(fullMsg[:msgLength])
            fullMsg = fullMsg[msgLength:]
            newMsg = True
    interString = interclass(messages[0],messages[1])
    conn.sendall(bytes(interString,'utf-8'))
conn.close()

该应用程序将一直运行,直到我尝试尝试从服务器发送数据的部分为止。所有这些都在客户端的recv()命令处阻塞。我在互联网上搜索了所有解决方案,然后尝试将其设置为非阻塞套接字并处理异常……仍然无法正常工作。我将不胜感激。谢谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。