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()

如有不对,请您指出。

你可能感兴趣的:(个人学习)