Python聊天室实现 Fay·D·Flourite

python聊天室实现

本来以为之前那个服务端和客户端就能实现,结果还是比预期的要复杂的多。不过也是真正写过后才有了更深刻的认识.

代码如下

  • 服务端

import socket
import threading
import select
import time


#取得ip地址及定义端口
host=socket.gethostname()
host_ip=socket.gethostbyname(host)
port=45535
server_addr=(host_ip,port)

#创建,绑定套接字
server=socket.socket()
server.bind(server_addr)

    
server.listen(20)
print("等待用户进行连接")

user_socket=[]  #保存用户的套接字

user_msgs=[]

echo="欢迎连接"

#定义收函数
def user_msgget(client):
    global user_msgs
    try:
        
        msg = client.recv(1024)
        print(msg.decode('utf-8'),type(msg))
        user_msgs.append(msg)
    except:
        pass

#定义发函数
def user_msgsend(client):
    global user_msgs
    try:
        #反馈信息
        if len(user_msgs) == 1:
            msg_send=user_msgs[0]
            msg_comefrom="%s:" %addr[0]
            client.send(msg_comefrom.encode()+msg_send.upper())
            user_msgs.remove(user_msgs[0])
    except:
        pass


def thread_get():
    global user_socket
    
    while True:
        for i in user_socket:

            try:
                thread_user=threading.Thread(target=user_msgget,args=(i,))
                thread_user.start()

            except:
                continue

def thread_send():
    global user_socket
    
    while True:
        for i in user_socket:

            try:
                thread_user=threading.Thread(target=user_msgsend,args=(i,))
                thread_user.start()

            except:
                continue


#启动收发线程
thread_users_get = threading.Thread(target=thread_get)
thread_users_send = threading.Thread(target=thread_send)

if __name__ == "__main__":

    thread_users_get.start()
    thread_users_send.start()

#主线程进行连接以及将用户加入用户列表
    while True:
        try:

            client,addr = server.accept()
            print("来自%s用户已连接" %addr[0])
            client.send(echo.encode())

            user_socket.append(client)
            
            client.setblocking(0)
        except:
            continue

  • 客户端

import socket
import threading
import select

global client
host=socket.gethostname()
host_ip="47.112.188.203"
port=45535

server_addr=(host_ip,port)


client=socket.socket()

client.connect(server_addr)
print("连接成功")


msg_recv=client.recv(1024).decode()
print(msg_recv)



def send_msg():

    while True:    
        msg_send=input('在此输入消息>>: ').strip()
        if len(msg_send) == 0:
            continue
        client.send(msg_send.encode('utf-8'))

def recieve_msg():

    while True:
        feedback=client.recv(1024)                           
        print(feedback.decode('utf-8'))

threads_client = threading.Thread(target=recieve_msg)

if __name__ == "__main__":

    threads_client.start()

    send_msg()


    client.close()  

中间还走了不少弯路,现在也依旧存在一点小毛病,不过至少能和对方正常交流了。也是有了更清楚的认识,什么事都要自己去尝试了才能了解到更多知识啊。