Python以TCP搭建小游戏服务器

#coding=UTF-8
'''
任务:密室逃脱(猜数字)客户端
作者:全淅亚
时间:2019.7.14
'''

import socket,threading
import time
import base64
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex

sign = 1 #线程信号

#AES加密数据密匙
AES_SECRET_KEY = 'B31F2A75FBF94099' #此处16|24|32个字符
IV = "1234567890123456"

class client(object):
    def connect(self):
        self.request = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
        self.request.connect(('127.0.0.1', 8080))

    def sendMsg(self):
        while True:
            msg = raw_input('')
            if msg == 'exit':
                self.endClient()
            #数据加密
            self.AES(msg,1)

    def recvMsg(self):
        while True:
            data = self.AES(msg='', s=2)
            if data == 'exit':
                self.endClient()
            print data

    def endClient(self):
        global sign
        sign = 0

    #数据加密解密
    def AES(self,msg,s):
        try:
            aes_encrypt = AES_ENCRYPT()
            if s == 1:
                msg = aes_encrypt.encrypt(msg)
                self.request.sendall(msg)
            if s == 2:
                data = self.request.recv(1024)
                data = aes_encrypt.decrypt(data)
                return data
        except:
            print 'Error: 服务器无法连接...'


#数据加密类
class AES_ENCRYPT(object):
    def __init__(self):
        self.key = AES_SECRET_KEY
        self.mode = AES.MODE_CBC

    #加密函数
    def encrypt(self, text):
        cryptor = AES.new(self.key, self.mode,IV)
        length = 16
        count = len(text)
        if count < length:
            add = (length - count)
            # \0 backspace
            text = text + ('\0' * add)
        elif count > length:
            add = (length - (count % length))
            text = text + ('\0' * add)
        self.ciphertext = cryptor.encrypt(text)
        #AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题,使用base64编码
        return b2a_hex(self.ciphertext)

    #解密函数
    def decrypt(self, text):
        cryptor = AES.new(self.key, self.mode,IV)
        plain_text = cryptor.decrypt(a2b_hex(text))
        return plain_text.rstrip('\0')

def main():
    c = client()
    try:
        c.connect()
    except:
        main()
    try:
        t1 = threading.Thread(target=c.sendMsg)
        t2 = threading.Thread(target=c.recvMsg)
        t1.setDaemon(True)
        t1.start()
        t2.setDaemon(True)
        t2.start()
    except:
        print "Error: 线程问题"

    while True:
        global sign
        if sign == 0:
            break
    print '退出游戏'

if __name__ == '__main__':
    main()



你可能感兴趣的:(程序员,python后台工程师,python,服务器客户端)