|
1 | | -import socket |
| 1 | +#! /usr/bin/python |
| 2 | + |
2 | 3 | import sys |
| 4 | +import socket |
3 | 5 |
|
4 | | -# Create a TCP/IP socket |
5 | 6 |
|
6 | | -# Bind the socket to the port |
7 | | -server_address = ('localhost', 50000) |
| 7 | +class EchoServer(object): |
| 8 | + """Interacts with Client, recieving and sending data.""" |
8 | 9 |
|
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.""" |
10 | 12 |
|
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): |
12 | 23 | # 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)) |
13 | 33 |
|
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 |
17 | 45 |
|
| 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)) |
18 | 56 | finally: |
19 | | - # Clean up the connection |
| 57 | + print "Closing Socket" |
| 58 | + echo_server.CloseSocket() |
| 59 | + |
| 60 | +main() |
0 commit comments