client.py
# coding:utf-8
import socket
import threading
outString = ''
inString = ''
nick = ''
# 发送
def DealOut(sock):
global outString, nick
while True:
outString = raw_input() # 输入
outString = nick + ':' + outString # 拼接
sock.send(outString) # 发送
# 接收
def DealIn(sock):
global inString
while True:
try:
inString = sock.recv(1024)
if not inString:
break
if outString != inString:
print inString
except:
break
# socket 服务端和客户端 服务端坚挺 客户端请求 链接确认
nick = raw_input('input your nickname:')
ip = raw_input('input the server ip address:')
# 创建套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建套接字
sock.connect((ip, 8877)) # 发起请求
sock.send(nick)
# 多线程 接收信息 发送信息
thin = threading.Thread(target=DealIn, args=(sock,)) # 创建接收信息的线程
thin.start()
thout = threading.Thread(target=DealOut, args=(sock,)) # 创建发送信息的线程
thout.start()
server.py
# coding:utf-8
# 服务端
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) # 创建套接字
print 'Socket created'
s.bind((HOST, port)) # 套接字绑定到ip地址
s.listen(10) # 监听
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!') # 出现异常就退出
print data
return
# 发送的方法
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() # 当前线程放弃对资源占有, 通知所有
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()