Skip to content

Commit 4e642ad

Browse files
committed
Create echo_server.py
1 parent 15688a2 commit 4e642ad

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

socket/echo_server.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
'a server example which send hello to client.'
5+
6+
import time, socket, threading
7+
8+
def tcplink(sock, addr):
9+
print 'Accept new connection from %s:%s...' % addr
10+
sock.send('Welcome!')
11+
while True:
12+
data = sock.recv(1024)
13+
time.sleep(1)
14+
if data == 'exit' or not data:
15+
break
16+
sock.send('Hello, %s!' % data)
17+
sock.close()
18+
print 'Connection from %s:%s closed.' % addr
19+
20+
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
21+
# 监听端口:
22+
s.bind(('127.0.0.1', 9999))
23+
s.listen(5)
24+
print 'Waiting for connection...'
25+
while True:
26+
# 接受一个新连接:
27+
sock, addr = s.accept()
28+
# 创建新线程来处理TCP连接:
29+
t = threading.Thread(target=tcplink, args=(sock, addr))
30+
t.start()

0 commit comments

Comments
 (0)