這篇文章將為大家詳細(xì)講解有關(guān)Python中socket如何實現(xiàn)簡單聊天室,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

具體內(nèi)容如下
服務(wù)端使用了select模塊,實現(xiàn)了對多個socket的監(jiān)控。客戶端由于select在Windows下只能對socket使用,所以使用了多線程來實現(xiàn)對客戶端輸入和socket連接的同時監(jiān)控。注意這里的socket設(shè)置為了非阻塞。這樣就實現(xiàn)了在一個線程中同時進(jìn)行socket的接收和發(fā)送。
服務(wù)器代碼:
# -*- coding: utf-8 -*-
import socket,select
connection_list = []
host = ''
port = 10001
def board_cast(sock,message):
for socket in connection_list:
if socket != server_sock and socket != sock:
try:
socket.send(message)
except:
socket.close()
print str(socket.getpeername())+' is offline'
connection_list.remove(socket)
server_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
server_sock.setblocking(0)
server_sock.bind((host,port))
server_sock.listen(10)
connection_list.append(server_sock)
while 1:
readable,writable,error = select.select(connection_list,[],[])
for sock in readable:
if sock == server_sock:
connection,connection_add = sock.accept()
message = str(connection_add)+'enter room'
board_cast(connection,message)
print connection_add,'%s connect'
connection_list.append(connection)
else:
try:
date = sock.recv(1024)
print date
board_cast(sock,'('+str(sock.getpeername())+') :'+date)
except:
message2 = str(sock.getpeername())+ 'is offline'
board_cast(sock,message2)
print str(sock.getpeername())+ ' is offline'
sock.close()
connection_list.remove(sock)
continue客戶端代碼:
# -*- coding: utf-8 -*- import socket,threading,time flag = 0 date = '' lock = threading.Lock() host = 'localhost' port = 10001 client_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client_sock.setblocking(0) class Mythread1(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): global flag, date while 1: date = raw_input() if len(date): lock.acquire() flag = 1 lock.release() class Mythread2(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): global flag global date while 1: try: buf = client_sock.recv(1024) if len(buf): print buf except: pass if flag: try: client_sock.send(date) except socket.error, e: print e lock.acquire() flag = 0 lock.release() try: client_sock.connect((host,port)) print"連接成功" except socket.error,e: print e t1 = Mythread1() t2 = Mythread2() t1.start() t2.start()
關(guān)于“Python中socket如何實現(xiàn)簡單聊天室”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
文章名稱:Python中socket如何實現(xiàn)簡單聊天室-創(chuàng)新互聯(lián)
轉(zhuǎn)載源于:http://chinadenli.net/article30/dsghpo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供小程序開發(fā)、網(wǎng)站導(dǎo)航、網(wǎng)站收錄、建站公司、網(wǎng)站策劃、網(wǎng)站營銷
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容