Created
November 16, 2015 03:12
-
-
Save Noxwizard/1af8e50d7956f71cb527 to your computer and use it in GitHub Desktop.
This file contains 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
import tcp_socket | |
s = tcp_socket.tcp_socket() | |
s.connect('localhost', 5000) | |
s.send('hello world') | |
response = s.recv() | |
print 'Received: ' + response |
This file contains 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
import tcp_socket | |
s = tcp_socket.tcp_socket() | |
s.bind('0.0.0.0', 5000) | |
s.listen(1) | |
while True: | |
client, address = s.accept() | |
resp = client.recv(1024) | |
if resp: | |
print '{0}:{1} - {2}'.format(address[0], address[1], resp) | |
client.send(resp) | |
client.close() |
This file contains 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
import socket | |
class socketException(Exception): | |
pass | |
class tcp_socket: | |
def __init__(self): | |
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
def connect(self, host, port): | |
self.sock.connect((host, port)) | |
def send(self, msg, bytesToSend=None): | |
if bytesToSend is None: | |
bytesToSend = len(msg) | |
bytesSent = 0 | |
while bytesSent < bytesToSend: | |
sent = self.sock.send(msg[bytesSent:]) | |
if sent == 0: | |
raise socketException("Error encountered during send") | |
bytesSent += sent | |
def recv(self, bytesToRead=None): | |
fragments = [] | |
bytesRecvd = 0 | |
receiving = True | |
while receiving: | |
chunk = self.sock.recv(1024) | |
if chunk == '': | |
receiving = False | |
fragments.append(chunk) | |
bytesRecvd = bytesRecvd + len(chunk) | |
return ''.join(fragments) | |
def bind(self, host, port): | |
self.sock.bind((host, port)) | |
def listen(self, connections): | |
self.sock.listen(connections) | |
def accept(self): | |
return self.sock.accept() |
This file contains 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
import tcp_socket | |
def run(): | |
s = tcp_socket.tcp_socket() | |
s.connect('www.google.com', 80) | |
request = """GET / HTTP/1.0 | |
Host: www.google.com | |
Connection: close | |
""" | |
s.send(request) | |
print s.recv() | |
if __name__ == "__main__": | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment