客户端-使用python进行服务器套接字编程

时间:2018-07-26 16:46:40

标签: python sockets network-programming client-server communication

下面是我的三个脚本。我需要将消息从脚本1(Sensor.py)发送到脚本2(Client.py)。然后脚本2应该将消息发送到脚本3(Server.py)。 它在脚本2之前可以正常工作,但是在脚本3上未收到消息,并且recvfrom()一直在等待。没有错误,但脚本3不显示该消息。我正在使用UDP。请帮忙。

脚本1(Sensor.py)

from socket import *
from time import ctime

CLIENT_IP = '192.168.1.109'
PORT = 23567
BUFSIZE = 1024
ADDR = (CLIENT_IP, PORT)

udpCliSock = socket(AF_INET, SOCK_DGRAM)

while True:
    sendData = input("> ")
    if sendData is None:
        break
    udpCliSock.sendto(sendData.encode(), ADDR)

udpCliSock.close()

SCRIPT 2(Client.py)

from socket import *
from time import ctime

HOST = '192.168.1.103'
CLIENT_IP='192.168.1.109'
PORT = 5005
SENSOR_PORT_NO=23567
BUFSIZE = 1024
ADDR = (HOST, PORT)
CLIENT_ADDR=(CLIENT_IP,SENSOR_PORT_NO)

udpCliSock = socket(AF_INET, SOCK_DGRAM)
client = socket(AF_INET, SOCK_DGRAM)
client.bind(CLIENT_ADDR)
while True:

    print("...waiting for response...")
    #recv_data, ADDR = udpCliSock.recvfrom(BUFSIZE)
    recv_data, ADDR = client.recvfrom(1024)
    if recv_data is not None:
        recv_data = recv_data.decode()
        print("[%s]: receiving data from server %s:%s  :%s" % (ctime(),ADDR[0], ADDR[1], recv_data))

    sendData = recv_data
    udpCliSock.sendto(sendData.encode(), ADDR)

udpCliSock.close()

SCRIPT 3(Server.py)

from socket import *
from time import ctime

HOST = '192.168.1.103'
PORT = 5005
BUFSIZE = 1024
ADDR = (HOST, PORT)

udpSerSock = socket(AF_INET, SOCK_DGRAM)
udpSerSock.bind(ADDR)
while True:
    print("...waiting for message...")
    data, ADDR = udpSerSock.recvfrom(BUFSIZE)
    print(data.decode)
    if data is None:
        break
    print("[%s]: From Address %s:%s receive data: %s" % (ctime(),ADDR[0],ADDR[1], data.decode()))

udpSerSock.close()

1 个答案:

答案 0 :(得分:0)

问题在于,当您从传感器收到数据报时,在Client.py中,您正在覆盖服务器的地址。在这里:

recv_data, ADDR = client.recvfrom(1024)

ADDR以服务器的套接字地址开始,但是此函数用传感器的套接字地址覆盖该变量。因此,当您尝试发送时,您会将其发送回传感器(当然,它从来没有收到过)。

更好的方法是在开始时connect将套接字插入服务器。然后,您就可以使用send而不是sendto,因为地址不会更改。在那之后应该工作:

...
udpCliSock = socket(AF_INET, SOCK_DGRAM)
udpCliSock.connect(ADDR)                # <<<<<<===============
client = socket(AF_INET, SOCK_DGRAM)
client.bind(CLIENT_ADDR)
while True:
    print("...waiting for response...")
    recv_data, addr = client.recvfrom(1024)
    if recv_data is not None:
        recv_data = recv_data.decode()
        print("[%s]: receiving data from server %s:%s  :%s" % (ctime(),addr[0], addr[1], recv_data))
    sendData = recv_data
    udpCliSock.send(sendData.encode())  # <<<<<<===============
udpCliSock.close()