首次连接后,Python UDP套接字无效

时间:2018-04-02 20:05:41

标签: python udp client-server

我正在使用python进行简单的应用程序,它可以使用套接字并使用UDP协议。我有一个client.py和server.py。我想在无限循环中从客户端向服务器发送消息,并从服务器捕获resive消息。为了做到这一点,我有以下代码:

server.py

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 8000
print(host)
print(port)
serversocket.bind((host, port))

serversocket.listen(5)
print('server started and listening')
while 1:
    (clientsocket, address) = serversocket.accept()
    print("connection found!")
    data = clientsocket.recv(1024).decode()
    print(data)
    r = 'I can hear you by UDP!!!!'
    clientsocket.send(r.encode())

client.py

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 8000
addr = (host, port)
s.connect(addr)


def send(user_input):
    s.sendto(user_input.encode(), addr)
    data = s.recv(1024).decode()
    print('Server tell that: ', data)


while 1:
    if input('Exit? (y/n)') == 'y':
        break
    i = input('>> ')
    send(i)

s.close()

它工作正常,但是当我第二次尝试发送消息时,我的程序会在线停止

s.sendto(user_input.encode(), addr)

我不明白这一刻发生了什么。

1 个答案:

答案 0 :(得分:0)

如果您想为UDP构建服务器/客户端,则需要仔细阅读文档,以防止使用面向连接协议的API。

以下是UDP的一个工作示例 :(我在代码中添加了一些注释,然后您将看到调整它们的原因)。

服务器

对于一个UDP服务器,您需要使用一个套接字socket.SOCK_DGRAM而不是SOCK_STREAM进行初始化,然后绑定您想要的端口。

import socket

#The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.
serversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = "127.0.0.1"
port = 8000
print(host)
print(port)
serversocket.bind((host, port))

#serversocket.listen(5)  #--This method sets up and start TCP listener.
print('server started and listening')
while 1:
    #(clientsocket, address) = serversocket.accept() #---This passively accept TCP client connection, waiting until connection arrives (blocking)
    #print("connection found!")
    #data = clientsocket.recv(1024).decode() #This method receives TCP message
    data, addr = serversocket.recvfrom(2048)
    print(data)
    r = 'I can hear you by UDP!!!!'
    serversocket.sendto(r.encode(), addr)
serversocket.close()

<强>客户端:

对于一个UDP客户端,您需要使用socket.SOCK_DGRAM而不是SOCK_STREAM初始化一个套接字,然后使用sendto将数据发送到服务器。

import socket
#The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = "127.0.0.1"
port = 8000
addr = (host, port)
#s.connect(addr) #---This method actively initiates TCP server connection.


def send(user_input):
    s.sendto(user_input.encode(), addr)
    data = s.recvfrom(1024).decode()
    print('Server tell that: ', data)


while 1:
    if input('Exit? (y/n)') == 'y':
        break
    i = input('>> ')
    send(i)

s.close()

有关详细信息

检查Python Socket