標籤:技術 div pos bre 初始 socket recv while 屬性
1、python socket模組內建方法
2、tcp伺服器虛擬碼
3、tcp用戶端虛擬碼
4、socket模組屬性
5、一個簡單的tcp用戶端和服務端服務端代碼:
# encoding:utf-8from socket import *from time import ctimefrom datetime import *# 定義tcpServer監聽連接埠號碼HOST = ‘0.0.0.0‘PORT = 21567ADDR = (HOST, PORT)BUFFSIZE=1024# 初始化一個tcp sockettcpSvrSock = socket(AF_INET, SOCK_STREAM)tcpSvrSock.bind(ADDR)tcpSvrSock.listen(5)while True: print(‘[%s] wait for connection...‘%(datetime.now())) tcpClientSock, clientAddr = tcpSvrSock.accept() print(‘[%s] connect from: %s...‘%(datetime.now(),clientAddr)) while True: recieveData = tcpClientSock.recv(BUFFSIZE) if not recieveData: break print(‘[%s] 收到報文:%s‘ %(datetime.now(),recieveData.decode(‘utf-8‘))) sendData = input(‘> ‘) if not sendData: break tcpClientSock.send(bytes(sendData,‘utf-8‘)) tcpClientSock.close()tcpSvrSock.close()
用戶端代碼:
# encoding:utf-8from socket import *from datetime import *HOST = ‘127.0.0.1‘PORT = 21567ADDR = (HOST, PORT)BUFFSIZE=1024clientSocket=socket(AF_INET,SOCK_STREAM)clientSocket.connect(ADDR)while True: sendData=input(‘> ‘) if not sendData: break sendData=bytes(sendData, ‘utf-8‘) clientSocket.send(sendData) recieveData=clientSocket.recv(BUFFSIZE) if not recieveData: break print(recieveData.decode(‘utf-8‘))clientSocket.close()
Python核心編程(網路編程)