很多教程挺流氓的,不做基础介绍,以下是我个人总结笔记,如有错误还请斧正
TCP版本
TCP是有链接的
服务端
addr设置 bind listen accept 固定流程
from socket import *
from time import ctime
HOST = '127.0.0.1'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
if __name__ == "__main__":
print("=====================TCP服务器=====================");
print('等待客户端的连接...')
while True:
tcpCliSock, addr = tcpSerSock.accept()
try :
data = tcpCliSock.recv(BUFSIZ,MSG_WAITALL)
except Exception as e:
print("Exception:",e)
strData = str(data,encoding="utf8")
if not data:
continue
if "exit" in strData:
tcpCliSock.close()
print(strData)
tcpSerSock.close()
客户端
from socket import *
from time import sleep
print("=====================TCP客户端=====================");
HOST = '127.0.0.1'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
while True:
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
data = input('> ')
tcpCliSock.send(bytes(data, 'utf-8'))
tcpCliSock.close()
sleep(1)
运行效果
UDP版本
server
from socket import *
from time import ctime
host = ''
port = 13141
bufsize = 1024
addr = (host,port)
udpServer = socket(AF_INET,SOCK_DGRAM)
udpServer.bind(addr)
while True:
print('Waiting for connection...')
data,addr = udpServer.recvfrom(bufsize)
data = data.decode(encoding='utf-8').upper()
data = "at %s :%s"%(ctime(),data)
print(data)
udpServer.close()
client
from socket import *
host = '127.0.0.1'
port = 13141
bufsize = 1024
addr = (host,port)
udpClient = socket(AF_INET,SOCK_DGRAM)
while True:
data = input('>>> ')
if not data:
break
data = data.encode(encoding="utf-8")
udpClient.sendto(data,addr)
udpClient.close()
|