标签:
客户端用多线程接受来自多用户的请求,且永不退出。
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import socket
import threading, time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((‘127.0.0.1‘, 9999))
s.listen(5)
print ‘Waiting for connection...‘
def tcplink(sock, addr):
print ‘Accept new connection from %s:%s...‘ % addr
sock.send(‘Welcome!‘)
while True:
data = sock.recv(1023)
time.sleep(1)
if data == ‘exit‘ or not data:
break
sock.send(‘Hello, %s!‘ %data)
sock.close()
print ‘Connection from %s:%s closed.‘ % addr
while True:
sock, addr = s.accept()
#创建新进程来出来新的TCP连接
t = threading.Thread(target=tcplink, args=(sock, addr))
t.start()
#!/usr/bin/env python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((‘127.0.0.1‘, 9999))
print s.recv(1024)
for data in [‘Michael‘, ‘Tracy‘, ‘Sarah‘]:
s.send(data)
print s.recv(1024)
s.send(‘exit‘)
s.close()
标签:
原文地址:http://my.oschina.net/lvyi/blog/383825