I'm using the following code to forward strings from server 1 to server 2, and back, opening and closing the socket each time.
def ts1(data):
try:
ts_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("CONNECTED TO TS1")
except socket.error as err:
print('socket open error: {} \n'.format(err))
exit()
ts_addr = (args.server_location, args.tsport)
ts_sock.connect(ts_addr)
with ts_sock:
if stuff:
ts_sock.sendall(ts_data.encode('utf-8'))
print('sent to ts1: ' + hostname)
while True:
data2 = ts_sock.recv(512)
data2 = data2.decode('utf-8')
data2 = data2.strip()
print('data 2: ' + data2)
break
ts_sock.close()
return data2
Server 2's socket is created beforehand and is never closed manually, so it just receives data, does it's thing and sends it back:
with csockid:
while True:
# receive and decode
try:
data = csockid.recv(512)
data = data.decode('utf-8')
data = data.strip()
except ConnectionResetError:
print("==> ConnectionResetError")
pass
if data:
csockid.sendall(data.encode('utf-8'))
# print('sent')
if not data:
break
For some reason, the first string is sent and received back just fine, but the second time I try to connect to server 2 and send another string, I get:
ts_sock.connect(ts_addr)
ConnectionRefusedError: [Errno 111] Connection refused
Any help would be appreciated, I'm rather new to socket programming & python in general.