python实现UDP通讯

Environment

Client:Windows
Server:KaLi Linux(VM_virtul)
Network:Same LAN

Client

UDPClient.py

#-*- coding: utf-8 -*-
#@Time : 2021/3/27 17:30
#@Author : HUGBOY
#@File : UDPClient.py
#@Software: PyCharm

from socket import *

HOST = '192.168.1.xxx'
PORT = 666

address = (HOST, PORT)
s = socket(AF_INET, SOCK_DGRAM)

while True:
    message = input('Send message:')
    s.sendto(message.encode('ascii'), address)
    data = s.recvfrom(1024)
    print(data.decode('ascii'))

s.close()

Server

UDPServer.py

#-*- coding: utf-8 -*-
#@Time : 2021/3/27 17:35
#@Author : HUGBOY
#@File : UDPServer.py
#@Software: PyCharm

from socket import *

HOST = '192.168.1.xxx'
PORT = 666

s = socket(AF_INET, SOCK_DGRAM)

s.bind((HOST, PORT))

print('...Waiting for message...')

while True:
    data, address = s.recvfrom(1024)
    print('Accept message:' + data.decode('ascii'))
    Reply = input('Send message:')
    s.sendto(Reply.encode('ascii'),address)
s.close()

Effect

1.Server

2.Client

3.Server

4.Client

...

posted @ 2021-03-27 19:26  HUGBOY  阅读(1680)  评论(0编辑  收藏  举报