TCP程式設計之服務端和客戶端的開發

weixin_34127717發表於2018-08-14
13103243-e3a4d79f754beca9.png
image.png

程式碼如下:

伺服器程式碼:
import socket

#定義連線資訊
HOST = ''
PORT = 8080

ADDRESS = (HOST,PORT)
#定義一個讀寫的資料的快取資料大小
BUFFER = 1024
#建立一個tcp套接字物件
tcp_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#繫結主機埠號
tcp_server.bind(ADDRESS)

#監聽埠,引數—排隊的客戶端
tcp_server.listen(1)
while True:
    print("準備建立連線......")
    server_socket,addr = tcp_server.accept()
    print("client already connect! welcome to server: ", addr)
    while True:
        info = input("請輸入您要傳送的資訊:")
        server_socket.send(info.encode("gbk"))

        #接收客戶端傳送的資訊
        msg = server_socket.recv(BUFFER)
        print("client:",msg.decode('utf-8'))

        if msg == b'BYE':
            #關閉套接字,釋放資源
            server_socket.close()
            break

tcp_server.close()
客戶端程式碼:
import socket

#建立連線資訊
TARGET_HOST = '192.168.13.21'
TARGET_PORT = 8080
TARGET_ADDRESS = (TARGET_HOST,TARGET_PORT)
BUFFER = 1024

#建立一個客戶端的套接字物件
tcp_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#連線指定的主機
tcp_client.connect(TARGET_ADDRESS)

#收發訊息
while True:
    msg = tcp_client.recv(BUFFER)
    print("server:",msg.decode("gbk"))

    #傳送訊息
    info = input("請輸入您要傳送的資訊:")
    tcp_client.send(info.encode("UTF-8"))
    print("對方已收到您的資訊")
    if info == "BYE":
        tcp_client.close()
        break

print("客戶端退出!")

相關文章