1. 程式人生 > >pthon3環境下利用socket實現server,client互動例項

pthon3環境下利用socket實現server,client互動例項

1、例項要求

使用socket實現一個基於C/S架構的通訊程式

  • (1)客戶端傳送給伺服器請求,傳送表徵身份的使用者名稱和密碼(“admin”,“123456”);

  • (2)伺服器根據客戶端發來的資訊驗證身份,如果驗證錯誤,返回“refuse”字串,並且斷開連線通道;

  • (3)如果通過身份驗證,伺服器向客戶端返回“accept”字串;

  • (4)客戶端在收到“accept”後,傳送服務請求號,“1”表示請求檔案傳輸服務,“2”表示請求資料庫查詢服務;

  • (5)伺服器收到服務請求號後,用列印語句來模擬服務的動作,完成後返回“finish”字串;

  • (6)客戶端收到“finish”串後,向伺服器端傳送“byebye”,終止連線;

  • (7)雙方中斷連線,關閉socket。

2、原理

https://baike.baidu.com/pic/socket/281150/0/d000baa1cd11728b45647b06cafcc3cec3fd2c4c?fr=lemma&ct=single#aid=0&pic=d000baa1cd11728b45647b06cafcc3cec3fd2c4c

3、方法

https://docs.python.org/3.6/library/socket.html#module-socket

4、程式碼塊

socket_server.py

import socket
import threading
import time

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

server_socket.bind(('127.0.0.1', 12345))

server_socket.listen(5)
print("Waiting for connection...")

def tcplink(sock, addr):
    print('Accept new connection from %s:%s...' % addr)
    sock.send(b'welcome!')
    name = sock.recv(1024).decode('utf-8')
    sname = str(name)
    time.sleep(1)
    psd = sock.recv(1024).decode('utf-8')
    spsd = str(psd)
    print("The loginname is %s has login, and loginpasswd is %s." % (sname, spsd))

    if sname == "admin" and  spsd == "123456":
        msg1 = bytes('accept', encoding = 'utf-8')
        time.sleep(1)
        sock.send(msg1)
        requ_num = sock.recv(1024)
        print(requ_num)

        ms3 = bytes('finsh', encoding = 'utf-8')
#        print("ms3")
#        print(str(ms3))

        if str(requ_num) == "b'1'":
            print('The operqtion is 1.')
            file_op = bytes('Simulate the operation that file transfer!', encoding = 'utf-8')
            time.sleep(1)
            sock.send(file_op)
            sock.send(ms3)
            order1 = sock.recv(1024).decode('utf-8')

        elif str(requ_num) == "b'2'":
            print('The operqtion is 2.')
            sql_op = bytes('Simulate the operation that sql select!', encoding = 'utf-8')
            sock.send(sql_op)
            sock.send(ms3)
            order1 = sock.recv(1024)

#        print("test:", str(order1))
        if str(order1) == "byebye":
            print("Server get byebye!stop conn.")
            sock.close()
        else:
            pass

    else:
        msg2 = bytes('Refuse, plz check your loginname and passwd!', encoding = 'utf-8')
        sock.send(msg2)
        sock.close()

    while True:
#        data = sock.recv(1024)
        time.sleep(1)
#        if not data or data.decode('utf-8') == 'exit':
#            break
        break
    sock.close()
    print('Connection from %s:%s closed.' % addr)
    print("****over****\n")

n = 0#loginer

while True:

    sock, addr = server_socket.accept()
    # 建立新執行緒來處理TCP連線:
    new_t = threading.Thread(target = tcplink, args=(sock, addr))
    new_t.start()
    n = n + 1
    print("Here are %d loginer." % n)


socket_client.py

import socket
import time

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

client_socket.connect(('127.0.0.1', 12345))

print(client_socket.recv(1024).decode('utf-8'))

name = input('Plz input your loginname:')
bname = bytes(name, encoding = 'utf-8')
psd = input('Plz input your passward:')
bpsd = bytes(psd, encoding = 'utf-8')
client_socket.send(bname)
time.sleep(1)
client_socket.send(bpsd)

order1 = client_socket.recv(1024).decode('utf-8')
print(order1)
time.sleep(1)

if order1 =='accept':
    requests_ser_num = input("operation('1'表示請求檔案傳輸服務, '2'表示請求資料庫查詢服務):")
    b_requests_ser_num = bytes(requests_ser_num, encoding = 'utf-8')
    client_socket.send(b_requests_ser_num)

    op = client_socket.recv(1024).decode('utf-8')
    print(op)

    order2 = str(client_socket.recv(1024).decode('utf-8'))
    print("Receive the server's order: %s ." % (order2))

    if str(order2) == "finsh":
        ms1 = bytes('byebye', encoding='utf-8')
        print('Send the order "byebye" to server.')
        client_socket.send(ms1)

        # client_socket.send(b'exit')
        client_socket.close()
    else:
        pass

else:
    client_socket.close()

client_socket.close()

如有不對,請您指出