Python TCPclient不会承认

时间:2017-02-05 18:09:35

标签: python sockets tcp

我在python中编写一个TCP客户端,当它连接到服务器并回答它时需要从服务器获取数学问题。 我用Netcat连接到服务器并在Wireshark上看到了这个: enter image description here

当我用我的代码完成它时,我看到了这一点 enter image description here

唯一的区别是服务器发出问题后我的代码没有确认。

这是我的代码:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'x.x.x.x'
port = 1337
s.connect((host, port))

while 1:
    data = s.recv(1024)
    print(data)
    splited_data = data.splitlines()
    exercise = splited_data[-1].decode("utf-8")
    print(exercise) 
    exercise = splited_data[-1].split()
    num1 = int(exercise[0])
    arithmetic = exercise[1].decode("utf-8")
    num2 = int(exercise[2])

    if arithmetic == '+':
        answer = num1 + num2
    elif arithmetic == '-':
        answer = num1 - num2
    elif arithmetic == '*':
        answer = num1 * num2
    elif arithmetic == '/':
        answer = num1 / num2
    elif arithmetic == '%':
        answer = num1 % num2
    else:
        print(arithmetic)

    print(answer)
    print(str(answer).encode('utf-8'))
    s.send(str(answer).encode('utf-8'))

2 个答案:

答案 0 :(得分:0)

无论服务器使用哪种协议将这些问题封装到消息中,您的代码都没有相应的代码来接收此类消息。您需要遵循服务器正在使用的协议的文档,或者如果协议没有记录,则对其进行反向工程。

TCP是一种字节流协议,不保留应用程序消息边界。要实现消息,您需要编写消息层。你没有写过这样的代码。

每当两个程序要交换消息时,他们必须就如何标记和识别这些消息的开头和结尾达成一致。发件人必须具有代码,以便按照约定标记邮件的结尾。接收方必须有代码才能找到消息的结尾。您的接收器没有这样的代码,因此无法可靠地确定消息的结束位置。

答案 1 :(得分:0)

我会在你的while循环后面使用s.close()来结束连接。

在您的第一个Wireshark片段中,看起来一方无法正常关闭TCP连接。

相关问题