2024年10月7日 星期一

使用with..as情境管理器撰寫UDP/TCP程式

參考資料: Socket Programming in Python (Guide)

去年文章:用Python實作UDP傳送和接收程式用Python實作TCP傳送和接收程式

情境管理器(Context Managers,又稱上下文管理器):使用 with asContext Swith

範例一、UDP程式(注意,請開2個IDLE分別執行客戶端程式和伺服端程)

客戶端程式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import socket

PORT = 1060
network = '192.168.1.104'
message = '國立虎尾科技大學電機資訊學院有電機、光電、資訊、電子等系所'

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
    s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    s.sendto(message.encode('utf-8'), (network, PORT))
    data, address = s.recvfrom(65535)
    print('UDP Client 接收訊息來自 {}:\n{}'.format(address, data.decode('utf-8')

伺服端程式:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import socket

PORT = 1060
network = '192.168.1.104'
message = '國立虎尾科技大學電機資訊學院歡迎您'

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    s.bind((network, PORT))
    print('聆聽訊息來自 ', s.getsockname())
    while True:
        data, address = s.recvfrom(65535)
        print('UDP Server 接收訊息從 {}:\n{}'.format(address, data.decode('utf-8')))
        s.sendto(message.encode('utf-8'), address)

範例二、TCP程式
客戶端:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import socket

PORT = 1060
network = '192.168.1.104'
message = '國立虎尾科技大學電機資訊學院有電機、光電、資訊、電子等系所'

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((network, PORT))
    s.send(message.encode('utf-8'))
    data = s.recv(65535)
    print('TCP Client 接收訊息來自{}:\n{}'.format(network, data.decode('utf-8'))

伺服端:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import socket

PORT = 1060
network = '192.168.1.104'
message = '國立虎尾科技大學電機資訊學院歡迎您'

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((network, PORT))
    print('聆聽訊息來自 ', s.getsockname())
    s.listen(5)
    conn, address = s.accept()
    print('TCP Server is connected by ' + str(address))
    data = conn.recv(65535)
    print('TCP Server 接收訊息從 {}:\n{}'.format(address, data.decode('utf-8')))
    conn.send(message.encode('utf-8'))

沒有留言:

張貼留言