# 服务端 From Client, Scott: Hi! New msg:Hi Scott! From Client, Scott:Are you admin from the server? New msg:Yes, i am. From Client, Scott:Nice to meet you!!! New msg:Me too. How can i help you? From Client, Scott:Just test the connection, bye~ New msg:Ok, Have a great day! From Client, Scott:You too!
# 客户端 From Server, Admin:Hi Scott! New msg:Are you admin from the server? From Server, Admin:Yes, i am. New msg:Nice to meet you!!! From Server, Admin:Me too. How can i help you? New msg:Just test the connection, bye~ From Server, Admin:Ok, Have a great day! New msg:You too!
Socket 实现多用户聊天
上面的 server 只支持一个用户,如何支持多个用户呢?可以使用线程来实现,背后的思想是,每当遇到一个新的连接 请求,就让一个线程去处理, 也就是这一段 sock_client, addr = server.accept() 交给一个新的线程去处理。
From Client 1, Scott: Hi! New msg:Hi Scott! From Client 2, The Weeknd: Hi! New msg:Hi The Weeknd! From Client 1, Scott:I really like the weeknd! New msg:Me too! From Client 2, The Weeknd:I just adds three tracks to my new album: Dawn FM. New msg:Great!