Skip to content

Commit 0fc59a2

Browse files
committed
This is the updated file
1 parent 38ea0a1 commit 0fc59a2

1 file changed

Lines changed: 51 additions & 10 deletions

File tree

Lines changed: 51 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,60 @@
1-
import socket
1+
#! /usr/bin/python
2+
23
import sys
4+
import socket
35

4-
# Create a TCP/IP socket
56

6-
# Bind the socket to the port
7-
server_address = ('localhost', 50000)
7+
class EchoServer(object):
8+
"""Interacts with Client, recieving and sending data."""
89

9-
# Listen for incoming connections
10+
def __init__(self, host="127.0.0.1", port=50000, backlog=5):
11+
"""Constructs the socket connection, configures the server."""
1012

11-
while True:
13+
# Create a TCP/IP socket
14+
self.server = socket.socket(2, 1, 0)
15+
# Bind the socket to the port
16+
self.server.bind((host, port))
17+
print 'Server started on port: ', port
18+
# Listen for incoming connections
19+
self.server.listen(backlog)
20+
print("Server listening\n")
21+
22+
def ProcessRequest(self):
1223
# Wait for a connection
24+
self.con, self.cli = self.server.accept()
25+
print 'New connection from ', self.cli
26+
self.data = self.con.recv(1024)
27+
print "Client Request: " + self.data
28+
return self.data
29+
30+
def ProcessResponse(self, response):
31+
# Send data to client
32+
self.con.sendall('The result is ' + str(response))
1333

14-
try:
15-
# Receive the data and send it back
16-
34+
def DoMath(self, data):
35+
self.data = self.data.split()
36+
if self.data[1] == '+':
37+
result = int(self.data[0]) + int(self.data[2])
38+
elif self.data[1] == '-':
39+
result = int(self.data[0]) - int(self.data[2])
40+
elif self.data[1] == '*':
41+
result = int(self.data[0]) * int(self.data[2])
42+
elif self.data[1] == '/':
43+
result = int(self.data[0]) / int(self.data[2])
44+
return result
1745

46+
def CloseSocket(self):
47+
self.con.close()
48+
49+
50+
def main():
51+
echo_server = EchoServer()
52+
while True:
53+
data = echo_server.ProcessRequest()
54+
try:
55+
echo_server.ProcessResponse(echo_server.DoMath(data))
1856
finally:
19-
# Clean up the connection
57+
print "Closing Socket"
58+
echo_server.CloseSocket()
59+
60+
main()

0 commit comments

Comments
 (0)