您好,登錄后才能下訂單哦!
這篇文章給大家介紹怎么在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。