Python--多线程网络编程

来源:互联网 发布:日本军国主义知乎 编辑:程序博客网 时间:2024/05/22 17:37

一、版本一:

 程序工作流程如下:

  • 用户连接上服务器
  • 发给服务器的第一句话:用户名
  • 判断第一句话是否存在再哈希表中
  • 存在用户名就拒绝连接(用户名已经存在,则不能再用这个用户名)
  • 不存在用户名,就将该用户名作为哈希表的键将存入哈希表中去
  • 并将该客户端的socket连接放到该用户名的哈希表的值中去
  • 然后为该用户创建一个处理线程
# -*- coding: utf-8 -*-from socket import *from time import ctimeimport threading     #多线程模块import re            #正则表达式模块HOST = 'localhost'PORT = 10000BUFSIZE = 1024ADDR = (HOST, PORT)tcpSerSock = socket(AF_INET, SOCK_STREAM)tcpSerSock.bind(ADDR)tcpSerSock.listen(5)clients = {}   # 提供 用户名->socket 映射chatwith = {}  # 提供通信双方映射def Deal(sock, user):    while True:        data = sock.recv(BUFSIZE)        if data == 'quit':  # 用户退出            del clients[user]            sock.send(data)            sock.close()            print '%s logout' % user            break        elif re.match('to:.+', data) is not None:  # 选择通信对象            data = data[3:]            if clients.has_key(data):                chatwith[sock] = clients[data]                chatwith[clients[data]] = sock            else:                sock.send('the user %s is not exist' % data)        else:            if chatwith.has_key(sock):  # 进行通信                chatwith[sock].send("[%s] %s: %s" % (ctime(), user, data))            else:                sock.send('Please input the user who you want to chat with')def Main():    while True:        print 'waiting...'        tcpCliSock, addr = tcpSerSock.accept()        print 'From:', addr        username = tcpCliSock.recv(BUFSIZE)  # 接收用户名        print 'Username:', username        if clients.has_key(username):    # 查找用户名            tcpCliSock.send("Reuse")     # 用户名已存在            tcpCliSock.close()        else:            tcpCliSock.send("Connected!")  # 登入成功            clients[username] = tcpCliSock # 将键值对匹配,便于通信            chat = threading.Thread(target=Deal, args=(tcpCliSock, username))  # 创建新线程进行处理            chat.start()  # 启动线程if __name__ == '__main__':    Main()

二、版本二

原创粉丝点击