在Python 3.6中通过TCP套接字发送列表时,为什么输出会有所不同?

时间:2018-04-25 02:23:33

标签: python list sockets server client

有人可以解释为什么我的套接字程序每次运行代码时都会以奇怪的方式输出消息。

我应该从客户端发送的列表中接收服务器结果,如下所示:

  

发送请求' E1.0 -945 1689 -950 230 -25 1'

     

收到回复:

     

发送请求' S0 2 -945 1689 -950 230 -25 1 1e-15'

     

收到回复:

     

...

相反,我明白了:

  

发送请求' E1.0 -945 1689 -950 230 -25 1'

     

收到回复:

     

发送请求' S0 2 -945 1689 -950 230 -25 1 1e-15'

     

收到回复:

     

发送请求' G4.1 0 0'收到回复:XIncorrect命令类型

     

发送请求' 4 1 0'

     

收到回复:XIncorrect命令类型

     

发送请求' E1.0'

     

收到回复:

     

发送请求' S1.0'收到回复:

     

发送请求' S0 2 -945 1689 -950 230 -25 1 -1e-15'收到回复:

     

发送请求'不是号码'收到回复:XIncorrect命令类型

这种情况一直都在发生,有时它会起作用,因为它应该在大多数时候收到的数据不合适。这是我的代码......

server.py

import socket
port = 12345
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mySocket.bind(('localhost', port))
mySocket.listen(0)
clientsocket, addr = mySocket.accept()
print("Connection from: {}\n".format(str(addr)))

while True:
    encoded_message = clientsocket.recv(2048)
    data = encoded_message.decode()
    print(data)
    if not data:
        break
    else:
        acknowledge = "Sending request \'{}\'".format(data)
        clientsocket.sendall(acknowledge.encode())
        request_code = data[0]
        if request_code == 'E':
            messageO = "Received response: \n\r"
            clientsocket.sendall(messageO.encode())
        elif request_code == 'S':
            messageO = "Received response: \n\r"
            clientsocket.sendall(messageO.encode())
        else:
            messageO = "Received response: XIncorrect command type\n\r"
            clientsocket.sendall(messageO.encode())

clientsocket.close()

client.py

import socket
host = 'localhost'
port = 12345

mySocket = socket.socket()
mySocket.connect((host, port))

testing_strings = ["E1.0 -945 1689 -950 230 -25 1",
                   "S0 2 -945 1689 -950 230 -25 1 1e-15",
                   "G4.1 0 0",
                   "4 1 0",
                   "E1.0",
                   "S1.0",
                   "S0 2 -945 1689 -950 230 -25 1 -1e-15",
                   "Not a number",
                   "S0 2 -945 1689 -950 230 -25 1 0",
                   "S0 2 -945 1689 -950 230 G 1 1e-15"]

count = 0
print(len(testing_strings))
count = 0
for l in testing_strings:
    if count == (len(testing_strings)-1):
        mySocket.send(l.encode())
        data = mySocket.recv(2048).decode('utf-8')
        print(data)
        mySocket.shutdown(1)
    else:
        mySocket.send(l.encode())
        data = mySocket.recv(2048).decode('utf-8')
        print(data)
        count += 1

mySocket.close()

0 个答案:

没有答案