-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket_server.py
More file actions
73 lines (61 loc) · 1.69 KB
/
socket_server.py
File metadata and controls
73 lines (61 loc) · 1.69 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
__author__ = 'syedaali'
'''
Sample program to demonstrate a socket based server in Python
Once you run this program, you can telnet to port 9000 and type in
random characters.
The basic process of socket connection is:
- Create socket
- Bind
- Listen
- Accept
- Receive data
- Send reply if needed
- Close connection
'''
import socket
import sys
from thread import *
import signal
def sig_handler(signum, stack):
print '\nReceived signal, quitting'
sys.exit(0)
signal.signal(signal.SIGINT,sig_handler)
#function that is called once you listen to a port
def clientthreads(conn):
conn.send('Hello, say something\n')
while True:
data = conn.recv(2048)
reply = 'Got -> {}'.format(data)
if not data:
break
conn.sendall(reply)
conn.close()
def main():
#listening to all interfaces on port 9000
HOST = ''
PORT = 9000
#create a socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#try to bind to port
try:
s.bind((HOST,PORT))
except socket.error as msg:
print 'Unable to bind {0} with message {1}'.format(str(msg[0]),msg[1])
sys.exit(1)
else:
print 'Socket bind complete'
#after binding to port, start to listen
s.listen(10)
print 'Socket now listening'
#now that we are listening, we are ready to accept
#we call our function clientthreads once we connnect
while 1:
#this is a blocking call
conn, addr = s.accept()
print 'Connected with {0} : {1}'.format(addr[0],str(addr[1]))
#here is where we multi-thread
start_new_thread(clientthreads ,(conn,))
s.close()
if __name__=='__main__':
main()