TCP:

服务端:

from socket import *

from time import ctime

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

tcpserverSock = socket(AF_INET, SOCK_STREAM)
tcpserverSock.bind(ADDR)
tcpserverSock.listen(5)

while True:
    print('dengdai lianjie:')
    tcpCliSock, addr = tcpserverSock.accept()
    print('laizi lianjie:', addr)
    while True:
        data = tcpCliSock.recv(BUFSIZE)
        if not data:
            break
        tcpCliSock.send(('HAHA:[%s] %s' % (bytes(ctime(), 'utf-8'), data)).encode())
    tcpCliSock.close()

客户端:

from socket import *

HOST = '127.0.0.1'
PORT = 40000
BUFSIZE = 1024
ADDR = (HOST, PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
    clientdata = input('input:')
    if not clientdata:
        break
    tcpCliSock.send(clientdata.encode())
    serverdata = tcpCliSock.recv(BUFSIZE)
    if not serverdata:
        break
    print(serverdata.decode('utf-8'))
tcpCliSock.close()

 

UDP:

服务端:

from socket import *

from time import ctime

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

udpserverSock = socket(AF_INET, SOCK_DGRAM)
udpserverSock.bind(ADDR)

while True:
    print('dengdai lianjie:')
    data, addr = udpserverSock.recvfrom(BUFSIZE)
    t = '[%s] %s' % (ctime(), data)
    udpserverSock.sendto(('HAHA:%s' % t).encode(), addr)
    print('huhu', addr)
udpserverSock.close()

客户端:

from socket import *

HOST = 'localhost'
PORT = 50000
BUFSIZE = 1024
ADDR = (HOST, PORT)

udpCliSock = socket(AF_INET, SOCK_DGRAM)

while True:
    clientdata = input('input:')
    if not clientdata:
        break
    udpCliSock.sendto(clientdata.encode(), ADDR)
    data, addr = udpCliSock.recvfrom(BUFSIZE)
    if not data:
        break
    print(data.decode('utf-8'))
udpCliSock.close()