socket UDP 서버 및 클라이언트 생성

3129 단어 socket

서버측 코드:
from socket import *
from time import ctime

HOST = ''
PORT = 1234
ADDR = (HOST, PORT)
BUFSIZE = 1024

def main():
udpSer = socket(AF_INET, SOCK_DGRAM)
udpSer.bind(ADDR)
while True:
print('waiting for message...')
data, adr = udpSer.recvfrom(BUFSIZE) # recvfrom ( , )
data = '[%s]%s' % (ctime(), data.decode('UTF-8'))
udpSer.sendto(bytes(data, 'UTF-8'), adr) # sento adr
print('...received from and returned to:', adr)

udpSer.close()

main()

클라이언트 코드:
from socket import *
from time import ctime

HOST = 'LOCALHOST'
PORT = 1234
ADDR = (HOST, PORT)
BUFSIZE = 1024

def main():
udpCli = socket(AF_INET, SOCK_DGRAM)
while True:
data = input('>')
if not data:
break;
udpCli.sendto(bytes(data, 'UTF-8'), ADDR)
data, addr= udpCli.recvfrom(BUFSIZE)
data = data.decode('UTF-8')
if not data:
break;
print (data)
udpCli.close()

main()

좋은 웹페이지 즐겨찾기