习题18-6
服务器
#-*-coding: utf-8-*-
# 参考网上的思路,服务器端主线程仍然是监视连接,新建两个线程,一个用来接收信息,另外一个用来接收信息。
from socket import *
import threading
from time import ctime
HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
def read(tcpCliSock):
while True:
rdata = tcpCliSock.recv(BUFSIZ)
if not rdata:
break
print rdata
def write(tcpCliSock):
while True:
sdata = raw_input('> ')
if not sdata:
break
tcpCliSock.send(sdata)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print "waiting for connection..."
tcpCliSock, addr = tcpSerSock.accept()
print "...connected from:", addr
r = threading.Thread(target=read, args=(tcpCliSock,)) # 接收信息线程
r.setDaemon(True) # 把接收信息线程设为守护线程,让主线程得以继续监视连接
r.start()
s = threading.Thread(target=write, args=(tcpCliSock,)) # 发送消息线程
s.setDaemon(True) # 同上,把发送消息线程也设为守护线程,让主线程得以继续监视连接
s.start()
tcpCliSock.close()
客户端
#-*-coding: utf-8-*-
# 客户端的思路不同,因为客户端只面对一个服务器,所以主线程可以选择为接受信息,而新建一个线程用来发送信息
import threading
from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
def write(tcpCliSock):
while True:
sdata = raw_input('> ')
if not sdata:
break
tcpCliSock.send(sdata)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
t = threading.Thread(target=write, args=(tcpCliSock,)) # 发送信息线程
t.setDaemon(True) # 将发送信息线程设为守护线程,让主线程得以接受来自服务器的信息
t.start()
while True:
rdata = tcpCliSock.recv(1024)
if not rdata:
break
print rdata
tcpCliSock.close()