2022年1月7日 星期五

Python Socket TCP Server/Client 通訊流程

Python Socket TCP Server/Client 通訊流程

源自於https://shengyu7697.github.io/python-tcp-socket/

 # -*- coding: utf-8 -*-

'''

TCP Server 的流程分為以下幾大步驟:

建立socket:s = socket.socket(socket.AF_INET, socket.SOCK_STREAM),指定 socket.AF_INET (Internet Protocol) family 的通訊協定,類型使用 socket.SOCK_STREAM (Stream Socket) 也就是 TCP 傳輸方式

綁定 socket 到本地 IP 與 port:s.bind()

開始監聽:s.listen()

等待與接受客戶端的請求連線:s.accept()

接收客戶端傳來的資料:s.recv()

傳送給對方發送資料:s.send()、s.sendall()

傳輸完畢後,關閉 socket:s.close()

'''

import socket

HOST = '127.0.0.1'

PORT = 7002

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

s.bind((HOST, PORT))

s.listen(5)


print('server start at: %s:%s' % (HOST, PORT))

print('wait for connection...')


while True:

    conn, addr = s.accept()

    print('connected by ' + str(addr))


    while True:

        indata = conn.recv(1024)

        if len(indata) == 0: # connection closed

            conn.close()

            print('client closed connection.')

            break

        print('recv: ' + indata.decode())


        outdata = 'echo ' + indata.decode()

        conn.send(outdata.encode())




# -*- coding: utf-8 -*-
'''
TCP Client 的流程分為以下幾大步驟:

建立 socket:s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
連線至遠端地址:s.connect()
傳送資料:s.send()、s.sendall()
接收資料:s.recv()
傳輸完畢後,關閉 socket:s.close()
'''
import socket

HOST = '127.0.0.1'
PORT = 7002

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

while True:
    outdata = input('please input message: ')
    print('send: ' + outdata)
    s.send(outdata.encode())
    
    indata = s.recv(1024)
    if len(indata) == 0: # connection closed
        s.close()
        print('server closed connection.')
        break
    print('recv: ' + indata.decode())

沒有留言:

張貼留言

WOKWI LED + MQTT Node-Red SQLite

WOKWI LED + MQTT Node-Red SQLite const char *mqtt_broker = "broker.mqtt-dashboard.com" ; const char *topic1 = "alex9ufo/e...