带有长消息的Python TCP socket.error

时间:2016-10-11 12:46:12

标签: python sockets tcp

我试图通过Python中的TCP在LAN网络上发送基本消息。 TCPClient.py:

import socket, sys, time

TCP_IP = "10.0.0.10"
TCP_PORT = 5005
BUFFER_SIZE = 1024
running = True

while running == True:
    try:
        MESSAGE = raw_input("Message: ")
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print("Connecting...")
        s.connect((TCP_IP,TCP_PORT))
        print("Connected!")
        s.send(MESSAGE)
        data = s.recv(BUFFER_SIZE)
        s.close()

        print("Sent data: %s" % MESSAGE)
        print("Recieved data: %s" % data)
        running = False
        time.sleep(20)
    except socket.error as e:
        print(e)
        time.sleep(1)
    except:
        print(sys.exc_info()[0])
        time.sleep(1)

和TCPServer.py:

import socket, time, sys

TCP_IP = "10.0.0.10"
TCP_PORT = 5005
BUFFER_SIZE = 20

while True:
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((TCP_IP,TCP_PORT))
        print("Listening for connection...")
        s.listen(1)

        conn,addr = s.accept()
        while 1:
            data = conn.recv(BUFFER_SIZE)
            if not data: break
            print("Recieved data: %s" % data)
            conn.send(data.upper())
            print("Sent data: %s" % data.upper())
        conn.close()
    except TypeError as e:
        print(e)
    except ValueError as e:
        print(e)
    except socket.error as e:
        print(e)
    except:
        print(sys.exc_info()[0])
        time.sleep(1)

它主要适用于小消息(例如" hello world")但是当我发送超过10个字符的消息时,它会将其分成2个部分,有时甚至不发送一半的消息。 E.g:

running both scripts

感谢先进的任何帮助!非常感谢。

1 个答案:

答案 0 :(得分:0)

以下是发生的事情:

  1. 您的客户发送了长队
  2. 您的服务器有20个字符的长行(服务器端缓冲区的大小)
  3. 您的服务器将数据(行的20个字符)发送回客户端
  4. 您的客户端获取数据并与服务器断开连接,导致服务器引发异常。