您的位置:首页 > 理论基础 > 计算机网络

Python2 socket TCPServer 多线程并发 超时关闭

2017-09-14 22:27 771 查看
在阿里云上测试过,可以直接使用。

用IP和端口发送数据,会返回echo:+接收到的数据

#coding=utf-8
import socket
import threading,getopt,sys,string
list=50
port=8001

opts, args = getopt.getopt(sys.argv[1:], "hp:l:",["help","port=","list="])
#设置默认的最大连接数和端口号,在没有使用命令传入参数的时候将使用默认的值

def usage():
print """
-h --help             print the help
-l --list             Maximum number of connections
-p --port             To monitor the port number
"""
for op, value in opts:
if op in ("-l","--list"):
list = string.atol(value)
elif op in ("-p","--port"):
port = string.atol(value)
elif op in ("-h"):
usage()
sys.exit()

def jonnyS(client, address):
try:
#设置超时时间
client.settimeout(30)
while True:
#接收数据的大小
buf = client.recv(2048)

print"connect by",address
print buf
#将接收到的信息原样的返回到客户端中
client.send("echo:"+buf)
#超时后显示退出
except socket.timeout:
print 'time out'
#关闭与客户端的连接
client.close()

def main():
#创建socket对象。调用socket构造函数
#AF_INET为ip地址族,SOCK_STREAM为流套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""  # 主机名,可以是ip,像localhost的主机名,或""
port = 9097  # 端口
addr = (host, port)
sock.bind(addr)
#设置最多连接数
sock.listen(list)
print "in loop!"
while True:
#服务器套接字通过socket的accept方法等待客户请求一个连接
client,address = sock.accept()
thread = threading.Thread(target=jonnyS, args=(client, address))
thread.start()

if __name__ == '__main__':
print "main running"
main()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: