参考python 核心编程 2 第472页TCP服务器和客户端的例子,实现双方对话。
加入线程的概念,实现单方多次发送信息。
注:在Python 核心编程 的这个例子本身有点问题,书上的第27行代码(本贴服务器代码的第32行)应该是一个TAB缩进,而不是两个TAB缩进
运行的时候请先运行 服务端 。
服务器(后附文件下载):
#tstserv.py
import thread
from socket import *
from time import ctime
'''TCP Server,core PYTHON programming P472'''
HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)
#PORT = raw_input('Port:')
#if not PORT:
# PORT = 21567
tcpSerSock = socket(AF_INET,SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(1)
print 'Enter out!'
while True:
print 'waiting for connecting...'
tcpCliSock,addr = tcpSerSock.accept()
print '...connected from:',addr
def priWord():
while True:
data = tcpCliSock.recv(BUFSIZ)
if data:
print ':',data,'\n>',
thread.start_new_thread(priWord,())
while True:
reWord = raw_input('>')
if not reWord:
break
tcpCliSock.send(reWord)
tcpCliSock.close()
if not raw_input('\nEnter out :'):
break
#t.exit()
tcpSerSock.close()
服务端测试结果:
Enter out!
waiting for connecting...
...connected from: ('127.0.0.1', 4340)
>向客户端发信息
>我再发
>: ok
> : again
>
客户端(后附文件下载):
#tstlcnt.py
import thread
from socket import *
'''TCP Client,core PYTHON programming P472'''
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)
#PORT = raw_input('Port:')
#if not PORT:
# PORT = 21567
#HOST = raw_input('HOST:')
#if not HOST:
# HOST = 'localhost'
tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)
print 'Enter out!'
def priWord():
while True:
data = tcpCliSock.recv(BUFSIZ)
if data:
print ':',data,'\n>',
thread.start_new_thread(priWord,())
while True:
data = raw_input('>')
if not data:
break
tcpCliSock.send(data)
tcpCliSock.close()
#t.exit()
#atemp = raw_input('\nq out :')
客户端测试结果:
Enter out!
>: 向客户端发信息
> : 我再发
>ok
>again
>