我试图通过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:
感谢先进的任何帮助!非常感谢。
答案 0 :(得分:0)
以下是发生的事情: