Skip to content

Instantly share code, notes, and snippets.

@RonenNess
Last active August 30, 2018 08:30
Show Gist options
  • Save RonenNess/6125cbc149cbfd61edc732f9502ea926 to your computer and use it in GitHub Desktop.
Save RonenNess/6125cbc149cbfd61edc732f9502ea926 to your computer and use it in GitHub Desktop.
import threading
import socket
# listening to socket with random port
sd = socket.socket(socket.AF_INET)
sd.bind(('127.0.0.1', 0))
ip, port = sd.getsockname()
sd.listen(5)
# connect to socket from "client" side
def connect_as_client(ip, port):
print ("Connect to: %s:%d" % (ip, port))
sd = socket.socket(socket.AF_INET)
sd.connect((ip, port))
sd.send('hello')
threading.Thread(target=connect_as_client, args=(ip, port)).start()
# accept connection and print data we got as a test
client, addr = sd.accept()
print ("Got data: '%s'" % client.recv(1024))
raw_input()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment