您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章给大家介绍怎么在python中利用C/S模式实现聊天室功能,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
服务器端代码:
from socket import * from time import ctime HOST = '' PORT = 4568 BUFSIZE = 1024 ADDR = (HOST,PORT) tcpSerSocket = socket(AF_INET, SOCK_STREAM) tcpSerSocket.bind(ADDR) tcpSerSocket.listen(5) while True: print('waitint for connection...') tcpCliSocket, addr = tcpSerSocket.accept() print('connecting from: ', addr) while True: data = tcpCliSocket.recv(BUFSIZE) if not data: break print data msg = raw_input('>') tcpCliSocket.send('[%s] %s' % (ctime(), msg)) tcpCliSocket.close() tcpSerSocket.close()
客户端代码:
from socket import * HOST = 'localhost' PORT = 4568 BUFSIZE = 1024 ADDR = (HOST, PORT) tcpCliSocket = socket(AF_INET, SOCK_STREAM) tcpCliSocket.connect(ADDR) while True: data = raw_input('>>') if not data: break tcpCliSocket.send(data) data = tcpCliSocket.recv(BUFSIZE) if not data: break print data tcpCliSocket.close()
运行结果我就不截图了,如果还不会的就复制下来运行一遍。
上面只是最简单的入门,一点都不好使,问题多着。
下面看怎么实现全双工。全双工就是双方可任意给对方发送消息。
全双工明显要用到多线程。我们在主线程之外创建两个子线程,一个负责接收消息,另一个负责接受用户输入并发送消息。
服务器端代码:
#coding: utf-8 from socket import * from time import ctime import threading from sys import stdout HOST = '' PORT = 21567 BUFSIZE = 1024 ADDR = (HOST, PORT) def Send(sck): while True: data = raw_input('>') sck.send(data) def Deal(sck, addr): while True: data = sck.recv(BUFSIZE) if data == "quit": sck.close() break str = '\nfrom' + addr[0] + ':' + data + '\n>' stdout.write(str) chatSerSock = socket(AF_INET, SOCK_STREAM) chatSerSock.bind(ADDR) chatSerSock.listen(5) threads = [] while True: print 'waiting for connection...' chatCliSock, addr = chatSerSock.accept() print "...connected from: ", addr t = threading.Thread(target=Deal, args=(chatCliSock, addr)) threads.append(t) t = threading.Thread(target=Send, args=(chatCliSock,)) threads.append(t) for i in range(len(threads)): threads[i].start() threads[0].join() chatCliSock.close() chatSerSock.close()
客户端代码:
#coding: utf8 from socket import * from time import ctime import threading from sys import stdout def Send(sck, test): while True: data = raw_input('>') sck.send(data) if data == "quit": break def Recieve(sck, test): while True: data = sck.recv(BUFSIZ) if data == "quit": sck.close() break str = "\nfrom server:" + data + "\n>" stdout.write(str) HOST = 'localhost' PORT= 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) threads = [] if __name__ == "__main__": chatCliSock = socket(AF_INET, SOCK_STREAM) chatCliSock.connect(ADDR) t = threading.Thread(target=Send, args = (chatCliSock, None)) threads.append(t) t = threading.Thread(target=Recieve, args = (chatCliSock, None)) threads.append(t) for i in range(len(threads)): threads[i].start() threads[0].join() chatCliSock.close()
运行结果:
关于怎么在python中利用C/S模式实现聊天室功能就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。