Created
November 17, 2013 16:53
-
-
Save techmaniack/7515423 to your computer and use it in GitHub Desktop.
python tcp ip example (addition of 2 numbers)
Example taken from http://docs.python.org/2/library/socket.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python | |
# Echo client program | |
import socket | |
def parse_file(fName): | |
list = [] | |
with open(fName) as f: | |
for line in f: | |
list.append(line.strip()) | |
return list | |
HOST = 'localhost' # The remote host | |
PORT = 50007 # The same port as used by the server | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
s.connect((HOST, PORT)) | |
# s.sendall('Hello, world') | |
# data = s.recv(1024) | |
# s.close() | |
# print 'Received', repr(data) | |
input_data = parse_file('foo') | |
for i in input_data: | |
s.sendall(str(i)) | |
sum = s.recv(1024) | |
print "CLIENT RECIEVED : Sum ", sum | |
s.close() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
12 | |
34 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python | |
# Echo server program | |
import socket | |
def compute_sum(line): | |
result = sum(int(i) for i in line) | |
return result | |
HOST = 'localhost' # Symbolic name meaning all available interfaces | |
PORT = 50007 # Arbitrary non-privileged port | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
s.bind((HOST, PORT)) | |
s.listen(1) | |
conn, addr = s.accept() | |
print 'Connected by', addr | |
while 1: | |
data = conn.recv(1024) | |
if not data: break | |
print "SERVER RECIEVED : ", repr(data) | |
compute_sum(data) | |
conn.sendall(data) | |
conn.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment