成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Python網絡編程的 11 個重要知識點

開發
網絡編程就是讓程序通過網絡發送數據給其他程序或接收其他程序的數據。Python中的網絡編程主要使用 socket 模塊。

1. 網絡編程基礎

網絡編程就是讓程序通過網絡發送數據給其他程序或接收其他程序的數據。Python中的網絡編程主要使用 socket 模塊。

2. TCP服務器示例

import socket

# 創建 socket 對象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 綁定端口
host = 'localhost'
port = 12345
server_socket.bind((host, port))

# 監聽連接
server_socket.listen(5)
print('Server listening on port:', port)

while True:
    # 建立客戶端連接
    client_socket, addr = server_socket.accept()
    print('Got connection from', addr)
    
    # 接收客戶端消息
    msg = client_socket.recv(1024).decode()
    print('Message from client:', msg)
    
    # 發送響應
    response = 'Thank you for connecting'
    client_socket.send(response.encode())
    
    # 關閉連接
    client_socket.close()

這個簡單的服務器監聽12345端口,當有客戶端連接時,會打印客戶端地址,并接收客戶端的消息,然后發送響應并關閉連接。

3. TCP客戶端示例

import socket

# 創建 socket 對象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 連接服務器
host = 'localhost'
port = 12345
client_socket.connect((host, port))

# 發送消息
msg = 'Hello, server!'
client_socket.send(msg.encode())

# 接收響應
response = client_socket.recv(1024).decode()
print('Response from server:', response)

# 關閉連接
client_socket.close()

這個簡單的客戶端連接服務器,發送一條消息,接收服務器的響應,并關閉連接。

4. UDP服務器示例

import socket

# 創建 socket 對象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 綁定端口
host = 'localhost'
port = 12345
server_socket.bind((host, port))

print('Server listening on port:', port)

while True:
    # 接收客戶端消息
    msg, addr = server_socket.recvfrom(1024)
    print('Message from client:', msg.decode(), 'at', addr)
    
    # 發送響應
    response = 'Thank you for your message'
    server_socket.sendto(response.encode(), addr)

這個簡單的UDP服務器監聽12345端口,接收客戶端的消息,然后發送響應。

5. UDP客戶端示例

import socket

# 創建 socket 對象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 發送消息
host = 'localhost'
port = 12345
msg = 'Hello, server!'
client_socket.sendto(msg.encode(), (host, port))

# 接收響應
response, addr = client_socket.recvfrom(1024)
print('Response from server:', response.decode())

# 關閉連接
client_socket.close()

這個簡單的UDP客戶端發送一條消息,接收服務器的響應,并關閉連接。

6. 多線程TCP服務器示例

import socket
import threading

def handle_client(client_socket, addr):
    print('Got connection from', addr)
    
    msg = client_socket.recv(1024).decode()
    print('Message from client:', msg)
    
    response = 'Thank you for connecting'
    client_socket.send(response.encode())
    
    client_socket.close()

# 創建 socket 對象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 綁定端口
host = 'localhost'
port = 12345
server_socket.bind((host, port))

# 監聽連接
server_socket.listen(5)
print('Server listening on port:', port)

while True:
    # 建立客戶端連接
    client_socket, addr = server_socket.accept()
    # 在新線程中處理客戶端連接
    thread = threading.Thread(target=handle_client, args=(client_socket, addr))
    thread.start()

這個服務器使用多線程處理多個客戶端連接,每個客戶端連接都在一個新線程中處理。

7. 非阻塞I/O TCP服務器示例

import socket
import select

# 創建 socket 對象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 設置為非阻塞模式
server_socket.setblocking(False)

# 綁定端口
host = 'localhost'
port = 12345
server_socket.bind((host, port))

# 監聽連接
server_socket.listen(5)
print('Server listening on port:', port)

inputs = [server_socket]
outputs = []

while True:
    readable, writable, exceptional = select.select(inputs, outputs, inputs)
    
    for sock in readable:
        if sock == server_socket:
            # 建立客戶端連接
            client_socket, addr = server_socket.accept()
            client_socket.setblocking(False)
            inputs.append(client_socket)
            print('Got connection from', addr)
        else:
            # 接收客戶端消息
            data = sock.recv(1024)
            if data:
                print('Message from client:', data.decode())
                sock.send(data.upper())
            else:
                # 客戶端斷開連接
                print('Client disconnected')
                inputs.remove(sock)
                sock.close()

這個非阻塞TCP服務器使用select模塊同時處理多個客戶端連接,提高了程序的響應速度。

8. 使用HTTP協議示例

from http.server import HTTPServer, BaseHTTPRequestHandler

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        message = 'Hello, World!'
        self.wfile.write(message.encode())

# 創建 HTTP 服務器
server_address = ('localhost', 8000)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)

print('Starting simple HTTP server...')
httpd.serve_forever()

這個簡單的HTTP服務器監聽8000端口,當收到GET請求時,返回“Hello, World!”的響應。

9. 發送HTTP請求示例

首先安裝requests庫:

pip install requests

然后編寫代碼:

import requests

url = 'http://localhost:8000'
response = requests.get(url)

print('Response status code:', response.status_code)
print('Response content:', response.text)

這段代碼向本地HTTP服務器發送GET請求,并打印響應的狀態碼和內容。

10. WebSocket編程示例

首先安裝websockets庫:

pip install websockets

然后編寫代碼:

import asyncio
import websockets

async def echo(websocket, path):
    async for message in websocket:
        print(f'Received message: {message}')
        await websocket.send(message)

# 創建 WebSocket 服務器
start_server = websockets.serve(echo, 'localhost', 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

這個簡單的WebSocket服務器監聽8765端口,當收到消息時,將其原樣返回。

11. 使用WebSocket客戶端示例

import asyncio
import websockets

async def send_message():
    uri = 'ws://localhost:8765'
    async with websockets.connect(uri) as websocket:
        message = 'Hello, WebSocket!'
        await websocket.send(message)
        print(f'Sent message: {message}')
        response = await websocket.recv()
        print(f'Received response: {response}')

asyncio.get_event_loop().run_until_complete(send_message())

這個簡單的WebSocket客戶端連接服務器,發送一條消息,并接收服務器的響應。

12. 實戰案例:實時聊天應用

接下來,我們將創建一個簡單的實時聊天應用,包括一個WebSocket服務器和多個客戶端。

(1) 創建WebSocket服務器

import asyncio
import websockets

connected_clients = set()

async def broadcast(message):
    if connected_clients:
        await asyncio.wait([client.send(message) for client in connected_clients])

async def chat(websocket, path):
    connected_clients.add(websocket)
    try:
        async for message in websocket:
            print(f'Received message: {message}')
            await broadcast(message)
    finally:
        connected_clients.remove(websocket)

# 創建 WebSocket 服務器
start_server = websockets.serve(chat, 'localhost', 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

這個WebSocket服務器監聽8765端口,并將所有客戶端的消息廣播給其他客戶端。

(2) 創建WebSocket客戶端

import asyncio
import websockets

async def chat_client():
    uri = 'ws://localhost:8765'
    async with websockets.connect(uri) as websocket:
        while True:
            message = input('Enter your message: ')
            await websocket.send(message)
            print('Sent message:', message)
            response = await websocket.recv()
            print('Received response:', response)

asyncio.get_event_loop().run_until_complete(chat_client())

這個WebSocket客戶端連接服務器,發送消息,并接收服務器的廣播消息。

責任編輯:趙寧寧 來源: 小白PythonAI編程
相關推薦

2020-02-07 09:59:29

Python異常處理語言

2020-10-14 10:50:50

SpringSessiJavaweb

2019-10-24 09:09:28

MySQLACIDJava

2021-04-13 08:25:12

測試開發Java注解Spring

2022-08-16 15:17:37

機器學習算法模型

2023-12-22 15:32:20

2021-04-19 08:35:44

PythonPython語言Python基礎

2020-09-25 16:52:57

Python

2024-11-06 17:00:34

Python嵌入式系統編程

2009-08-02 21:47:35

安防線纜

2022-08-01 07:42:17

線程安全場景

2021-04-29 10:01:30

JavaMathJava編程

2020-10-07 15:15:41

Python

2019-07-26 11:27:25

MySQLSQL數據庫

2021-01-15 08:35:49

Zookeeper

2018-01-29 15:23:14

網絡知識點軟件測試

2010-08-17 14:56:00

HCNE認證

2011-04-15 12:25:21

BGP路由

2024-09-09 23:15:55

2023-05-23 22:19:04

索引MySQL優化
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 亚洲成人午夜在线 | 亚洲自拍偷拍免费视频 | 成人在线小视频 | www久久久| 国产成人综合亚洲欧美94在线 | 国产免费福利小视频 | 久久久久久av | 五月婷婷视频 | 亚洲成人免费在线观看 | 日韩精品人成在线播放 | 欧洲妇女成人淫片aaa视频 | 国产精品嫩草影院精东 | av一区二区三区在线观看 | 国产一区二区三区www | 91综合在线观看 | 中文字幕国产视频 | 欧美aaaaa| 日韩一级精品视频在线观看 | 成人精品鲁一区一区二区 | 欧美视频三区 | 精品伦精品一区二区三区视频 | 欧美国产视频 | 亚洲精品美女视频 | 久久电影一区 | 亚洲伦理自拍 | 久久久亚洲 | 亚洲精品电影 | 日韩精品一区在线 | 亚洲精选一区二区 | 国产成人午夜电影网 | av电影一区二区 | 亚洲成人在线免费 | 亚洲v日韩v综合v精品v | 国精品一区二区 | 精品国产一区二区三区观看不卡 | 99久久99久久精品国产片果冰 | 精品日韩一区 | 国产精品久久久爽爽爽麻豆色哟哟 | 国产精品成人69xxx免费视频 | 2023亚洲天堂| 久久久久一区二区三区 |