-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathecho_serv.py
More file actions
39 lines (36 loc) · 1.28 KB
/
echo_serv.py
File metadata and controls
39 lines (36 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
import socket
import sys
import argparse
host = 'localhost'
data_payload = 2048
backlog = 5
def echo_server(port):
""" A simple echo server """
# Create a TCP socket. The first arg identifies the 'address family'.
# AF_INET6 could be used instead for IPv6. The second arg specifies the
# socket type. The stream type uses TCP/IP
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Enable reuse address/port
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Bind the socket to the port
server_address = (host, port)
print "Starting up echo server on %s port %s" % server_address
sock.bind(server_address)
# Listen to clients, backlog argument specifies the max no. of queued
# connections
sock.listen(backlog)
while True:
print "Waiting to receive message from client"
client, address = sock.accept()
data = client.recv(data_payload)
if data:
print "Data: %s" %data
client.send(data)
print "sent %s bytes back to %s" % (data, address)
client.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Socket Server Example')
parser.add_argument('--port', action="store", dest="port", type=int, required=True)
given_args = parser.parse_args()
port = given_args.port
echo_server(port)