! usr/bin/python34
# Echo server program
import socket
HOST = '' # 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))
print('Listening...')
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
#! usr/bin/python34
# Echo client program
import socket
HOST = '127.0.0.1' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Connecting...')
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
s.close()
print('Received', repr(data))
Sometimes the connection works other times it fails with:
Connecting...
Traceback (most recent call last):
File "/home/bgailer/socket_client.py", line 9, in <module>
s.connect((HOST, PORT))
ConnectionRefusedError: [Errno 111] Connection refused
I can't see any correlation between success and failure. Failure is about 80% of the time.