client.py
# coding:utf-8
import socket
import threading
outString = ''
inString = ''
nick = ''
# 發(fā)送
def DealOut(sock):
global outString, nick
while True:
outString = raw_input() # 輸入
outString = nick + ':' + outString # 拼接
sock.send(outString) # 發(fā)送
# 接收
def DealIn(sock):
global inString
while True:
try:
inString = sock.recv(1024)
if not inString:
break
if outString != inString:
print inString
except:
break
# socket 服務(wù)端和客戶端 服務(wù)端堅(jiān)挺 客戶端請求 鏈接確認(rèn)
nick = raw_input('input your nickname:')
ip = raw_input('input the server ip address:')
# 創(chuàng)建套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 創(chuàng)建套接字
sock.connect((ip, 8877)) # 發(fā)起請求
sock.send(nick)
# 多線程 接收信息 發(fā)送信息
thin = threading.Thread(target=DealIn, args=(sock,)) # 創(chuàng)建接收信息的線程
thin.start()
thout = threading.Thread(target=DealOut, args=(sock,)) # 創(chuàng)建發(fā)送信息的線程
thout.start()
server.py
# coding:utf-8
# 服務(wù)端
import socket
import threading
con = threading.Condition() # 條件
HOST = raw_input('input the server ip address:') # ip地址
port = 8877
data = ''
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 創(chuàng)建套接字
print 'Socket created'
s.bind((HOST, port)) # 套接字綁定到ip地址
s.listen(10) # 監(jiān)聽
print 'Socket now listening'
# 接收的方法
def clientThreadIn(conn, nick):
global data
while True:
try:
temp = conn.recv(1024)
if not temp:
conn.close()
return
NotifyAll(temp)
print data
except:
NotifyAll(nick + 'leaves the room!') # 出現(xiàn)異常就退出
print data
return
# 發(fā)送的方法
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
def NotifyAll(ss):
global data
if con.acquire(): # 獲取鎖 原子操作
data = ss
con.notifyAll() # 當(dāng)前線程放棄對資源占有, 通知所有
con.release()
while True:
conn, addr = s.accept() # 接收連接
print 'Connected with' + addr[0] + ':' + str(addr[1])
nick = conn.recv(1024) # 獲取用戶名
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()