Python核心編程(網路編程)

來源:互聯網
上載者:User

標籤:技術   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核心編程(網路編程)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.