1. 程式人生 > >Python socket實現簡單聊天室

Python socket實現簡單聊天室

服務端使用了select模組,實現了對多個socket的監控。客戶端由於select在Windows下只能對socket使用,所以使用了多執行緒來實現對客戶端輸入和socket連線的同時監控。注意這裡的socket設定為了非阻塞。這樣就實現了在一個執行緒中同時進行socket的接收和傳送。

伺服器程式碼

# -*- 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()