最簡單的模式,C/S模式實現聊天室
從半雙工開始,何謂半雙工?半雙工即是說雙方可以互發消息,但一次只能一個用戶發送。
只要稍微會點socket編程的人都會覺得很簡單,所以過過場,直接上代碼。
服務器端代碼:
from socket import *from time import ctime HOST = ''PORT = 4568BUFSIZE = 1024ADDR = (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 = 4568BUFSIZE = 1024ADDR = (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-8from socket import *from time import ctimeimport threadingfrom sys import stdout HOST = ''PORT = 21567BUFSIZE = 1024ADDR = (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: utf8from socket import *from time import ctimeimport threadingfrom sys import stdout def Send(sck, test): while True: data = raw_input('>') sck.send(data) if data == "quit": breakdef 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= 21567BUFSIZ = 1024ADDR = (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()
新聞熱點
疑難解答