插座,通讯停止

2024-09-24 04:24:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于套接字编程的简单问题。我已经按照下面的代码实现了一个服务器和两个客户机,但是突然之间它停止了,因为它彼此通信。我不知道为什么总是这样。在

你能给我建议、暗示或帮助吗?
谢谢你抽出时间。在

客户

# simple client

import socket
import sys

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = ""
port = 12345

buf = 100

s.connect((host, port))
i = 0

timestep = 0

while(1):
    k = '01'#+str(timestep)
    #1
    s.send(k)
    print 'sending message is', k

    #2
    v = s.recv(buf)
    print v

    if v == 'hold 01':
        print 'timestep is', timestep#'send the previous message'
        if timestep == 0:
            timestep == 0
        else:
            timestep -= 1
    else:
        print 'read data'
        FILE = open("datainfo1.txt", "r+")
        msg = FILE.read()
        FILE.close()

        #3
        while(1):
            tmp, msg = msg[:buf], msg[buf:]

            s.send(tmp)

            print len(tmp)

            if len(tmp) < buf:
                print 'break'
                break
        # send file
    i+=1
    timestep+=1
print 'end'
s.close()

服务器

^{pr2}$

Tags: import服务器sendhostmessageifportmsg
2条回答

一个问题是您正在设置非阻塞模式:

clnt.setblocking(0)

但不要检查发送或接收数据是否安全。结果是,由于代码忽略了所有异常,所以在删除try时没有看到以下错误:

Exception [Errno 10035] A non-blocking socket operation could not be completed immediately

删除setblocking调用后,代码继续执行,但仍然存在问题。在

描述您要解决的问题有助于理解代码要做什么。在

except: pass

你忽略了所有的例外。这是个坏主意,因为它不会让你知道什么时候出了问题。在合理地调试代码之前,您需要删除except处理程序。在

相关问题 更多 >