python socket之tcp服务器与客户端demo

python socket之tcp服务器与客户端demo

作者:vpoet

mails:vpoet_sir@163.com

server:

 1 # -*- coding: cp936 -*-
 2 '''
 3 建立一个python server,监听指定端口,
 4 如果该端口被远程连接访问,则获取远程连接,然后接收数据,
 5 并且做出相应反馈。
 6 '''
 7 import socket
 8 
 9 if __name__=="__main__":
10     print "Server is starting"
11     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
12     sock.bind(('localhost', 8001))  #配置soket,绑定IP地址和端口号
13     sock.listen(5) #设置最大允许连接数,各连接和server的通信遵循FIFO原则
14     print "Server is listenting port 8001, with max connection 5" 
15     while True:  #循环轮询socket状态,等待访问     
16         connection,address = sock.accept()  
17         try:  
18             connection.settimeout(10)
19             #获得一个连接,然后开始循环处理这个连接发送的信息
20             '''
21             如果server要同时处理多个连接,则下面的语句块应该用多线程来处理,
22             否则server就始终在下面这个while语句块里被第一个连接所占用,
23             无法去扫描其他新连接了,但多线程会影响代码结构,所以记得在连接数大于1时
24             下面的语句要改为多线程即可。
25             '''
26             while True:
27                 buf = connection.recv(1024)  
28                 print "Get value " +buf
29                 print  "\n\n"
30                 if buf=="q":
31                     print "exit server\n\n"
32                     break
33         except socket.timeout:  #如果建立连接后,该连接在设定的时间内无数据发来,则time out
34             print 'time out'
35 
36         print "closing one connection" #当一个连接监听循环退出后,连接可以关掉
37         connection.close()

 

client:

 1 import sys
 2 if __name__=="__main__":  
 3         import socket  
 4         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
 5         sock.connect(('localhost', 8001))  
 6         import time
 7         while True: 
 8                 time.sleep(3)  
 9                 flag=raw_input("Please input send flag:")
10                 if flag=="q":
11                     break
12                 sock.send(flag)   
13         sock.close()  

运行截图:


 

 

posted @ 2015-06-24 12:56  vpoet  阅读(488)  评论(0编辑  收藏  举报