参考例子,TCP服务器和客户端,加入线程的概念,实现单方多次发送信息(老手请路过)...

参考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
>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值