python網路編程實現TCP和UDP串連

來源:互聯網
上載者:User

標籤:socket   python   tcp   udp   

實現TCP

#!/usr/bin/env python3# -*- coding: utf-8 -*-import socket# 建立一個socket:s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 建立串連:s.connect((‘www.sina.com.cn‘, 80))# 發送資料:s.send(b‘GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n‘)# 接收資料:buffer = []while True:    # 每次最多接收1k位元組:    d = s.recv(1024)    if d:        buffer.append(d)    else:        breakdata = b‘‘.join(buffer)# 關閉串連:s.close()header, html = data.split(b‘\r\n\r\n‘, 1)print(header.decode(‘utf-8‘))# 把接收的資料寫入檔案:with open(‘sina.html‘, ‘wb‘) as f:    f.write(html)

實現UDP串連

服務端:#!/usr/bin/env python3# -*- coding: utf-8 -*-import sockets = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)# 綁定連接埠:s.bind((‘127.0.0.1‘, 9999))print(‘Bind UDP on 9999...‘)while True:    # 接收資料:    data, addr = s.recvfrom(1024)    print(‘Received from %s:%s.‘ % addr)    reply = ‘Hello, %s!‘ % data.decode(‘utf-8‘)    s.sendto(reply.encode(‘utf-8‘), addr)用戶端:#!/usr/bin/env python3# -*- coding: utf-8 -*-import sockets = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)for data in [b‘Michael‘, b‘Tracy‘, b‘Sarah‘]:    # 發送資料:    s.sendto(data, (‘127.0.0.1‘, 9999))    # 接收資料:    print(s.recv(1024).decode(‘utf-8‘))s.close()

python網路編程實現TCP和UDP串連

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.