forked from laike9m/learn_socket
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcp_server.py
More file actions
53 lines (39 loc) · 1.28 KB
/
tcp_server.py
File metadata and controls
53 lines (39 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import socket
import sys
from threading import Thread
HOST = '' # Symbolic name meaning all available interfaces
PORT = 1111 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
try:
s.bind((HOST, PORT))
except socket.error as msg:
print('Bind failed %s.' % msg)
sys.exit()
print('Socket bind complete')
s.listen(10)
print('Socket now listening')
# now keep talking with the client
def client_thread(conn):
conn.send('Welcome to the server. Type something and hit enter\n'.encode('utf-8'))
while True:
# wait to accept a connection - blocking call
data = conn.recv(1024).decode('utf-8')
reply = 'OK...' + data
if not data:
break
print(data)
conn.sendall(reply.encode('utf-8'))
conn.close()
def main():
while True:
# wait to accept a connection - blocking call
conn, addr = s.accept()
print('Connected with ' + addr[0] + ':' + str(addr[1]))
# start new thread takes 1st argument as a function name to be run,
# second is the tuple of arguments to the function.
new_conn = Thread(target=client_thread, args=(conn,))
new_conn.start()
s.close()
if __name__ == '__main__':
main()