簡體   English   中英

Python TCP/IP 套接字 - 按順序發送和接收消息

[英]Python TCP/IP socket - Sending and receiving messages in order

祝大家新年快樂!

我使用 Python 創建了一個套接字 TCP/IP。 在客戶端,我發送文本“A”和“B”,在服務器端,如果我收到正確的文本(A 和 B),我將向客戶端發送回復:“GOOD”。 一切都很好,直到我將文本的順序更改為“B”和“A”。

如何改進服務器端接收消息而不關心訂單 AB 或 BA。

服務器:

import socket

HOST = 'localhost'
PORT = 8019
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1) # Number of connections

# Server loop
while True:
    # Accept connections
    client, address = s.accept()
    print("Connected to", address)

    # Receive data and decode using utf-8
    data = client.recv( 1024 ).decode( 'utf-8' )
    print("Received :", repr(data))

    # Send data to client in utf-8
    if ("A" == data):
        reply = "GOOD"
        client.send(reply.encode('utf-8'))
    else:
        reply = "FAIL"
        client.send(reply.encode('utf-8'))
    # Receive data and decode using utf-8
    data = client.recv( 1024 ).decode( 'utf-8' )
    print("Received :", repr(data))

    # Send data to client in utf-8
    if ("B" == data):
        reply = "GOOD"
        client.send(reply.encode('utf-8'))
    else:
        reply = "FAIL"
        client.send(reply.encode('utf-8'))
    s.close()
    break

客戶:

import socket

# Create socket and connect it to server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost',8019))

# client loop
while True:
    message = "A"
    s.send(message.encode('utf-8'))
    print("Awaiting the reply...")
    reply = s.recv( 1024 ).decode( 'utf-8' )
    print("Received ", str(reply))
    
    message = "B"
    s.send(message.encode('utf-8'))
    print("Awaiting the reply...")
    reply = s.recv( 1024 ).decode( 'utf-8' )
    print("Received ", str(reply))
    s.close()
    break

任何幫助將不勝感激! 此致!

我想我可以做這樣的事情:

# Receive data and decode using utf-8
    data = client.recv( 1024 ).decode( 'utf-8' )
    print("Received :", repr(data))

    # Send data to client in utf-8
    if ("A" == data):
        reply = "GOOD"
        client.send(reply.encode('utf-8'))
    elif ("B" == data):
        reply = "GOOD"
        client.send(reply.encode('utf-8'))
    else:
        reply = "FAIL"
        client.send(reply.encode('utf-8'))


    # Receive data and decode using utf-8
    data = client.recv( 1024 ).decode( 'utf-8' )
    print("Received :", repr(data))

    # Send data to client in utf-8
    if ("A" == data):
        reply = "GOOD"
        client.send(reply.encode('utf-8'))
    elif ("B" == data):
        reply = "GOOD"
        client.send(reply.encode('utf-8'))
    else:
        reply = "FAIL"
        client.send(reply.encode('utf-8'))
    s.close()
    break

但我仍在等待更好的答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM