Python socket模拟聊天室(server)

连上server之后,会给每个client启动两个线程,同样处理接收和发送,唯一区别多了一个接收到输入后的激活所有输出线程的过程

server端

#!/usr/bin/env python

import socket
import sys
import threading
 
con = threading.Condition()
HOST = raw_input(“input the server’s ip adrress: “) # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
data = ”
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ‘Socket created’
s.bind((HOST, PORT))
s.listen(10)
print ‘Socket now listening’
 
#Function for handling connections. This will be used to create threads
def clientThreadIn(conn, nick):
    global data
#infinite loop so that function do not terminate and thread do not end.
    while True:
    #Receiving from client
        try:
            temp = conn.recv(1024)
            if not temp:
                conn.close()
                return
            NotifyAll(temp)
            print data
        except:
            NotifyAll(nick + ” leaves the room!”)
            print data
            return
 
    #came out of loop
 
def NotifyAll(sss):
    global data
    if con.acquire():
        data = sss
        con.notifyAll()
        con.release()
 
def ClientThreadOut(conn, nick):
    global data
    while True:
        if con.acquire():
            con.wait()
            if data:
                try:
                    conn.send(data)
                    con.release()
                except:
                    con.release()
                    return
                    
 
while 1:
    #wait to accept a connection – blocking call
    conn, addr = s.accept()
    print ‘Connected with ‘ + addr[0] + ‘:’ + str(addr[1])
    nick = conn.recv(1024)
     #send only takes string
    #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
    NotifyAll(‘Welcome ‘ + nick + ‘ to the room!’)
    print data
    print str((threading.activeCount() + 1) / 2) + ‘ person(s)!’
    conn.send(data)
    threading.Thread(target = clientThreadIn , args = (conn, nick)).start()
    threading.Thread(target = ClientThreadOut , args = (conn, nick)).start()
 
s.close()

运行结果:

(终端1)
lihui@LastWish /cygdrive/e/work $ python server.py
input the server’s ip adrress: localhost
Socket created
Socket now listening
Connected with 127.0.0.1:50960
Welcome jide to the room!
1 person(s)!
Connected with 127.0.0.1:51320
Welcome lihui to the room!
2 person(s)!
lihui: hello
jide: hello, too!

──────────────────────────────────────────────────────────────
(终端2)
lihui@LastWish /cygdrive/e/work $ python client.py
input your nickname: jide
input the server’s ip adrress: localhost
Welcome jide to the room!
Welcome lihui to the room!
lihui: hello
hello, too!

──────────────────────────────────────────────────────────────
(终端3)
lihui@LastWish /cygdrive/e/work $ python client.py
input your nickname: lihui
input the server’s ip adrress: localhost
Welcome lihui to the room!
hello
jide: hello, too!

发表评论