Python Forum
Socket - Keep Alive? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Networking (https://python-forum.io/forum-12.html)
+--- Thread: Socket - Keep Alive? (/thread-6423.html)



Socket - Keep Alive? - CDitty - Nov-21-2017

I am trying to write a small python program that just sends data out over a port socket. I can get it to work when there is a server that is listening, but I can't get it to work when there is nothing there. I've tried searching but haven't found anything that will work without a receiving server.

I am basically looking for a way that will attempt to connect, if it fails, wait X and try again.

Anyone have any suggestions or examples they can share?

This is what I have so far.....
Quote:import socket
import time
import string

host = '192.168.1.11' #socket.gethostname()
port = 9999
BUFFER_SIZE = 2000
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def testConnection(host, port, socket):
connected = False

while connected == False:
try:
socket.connect((host, port))
connected = True
socket.send("Hello")
except Exception as e:
print ("Exception is %s" % (e))
time.sleep(2)
connected = False

testConnection(host, port, socket)

And this is what I'm getting in return.
Quote:Exception is [Errno 61] Connection refused
Exception is [Errno 22] Invalid argument



RE: Socket - Keep Alive? - heiner55 - Nov-22-2017

See https://python-forum.io/Thread-File-Transfer


RE: Socket - Keep Alive? - Windspar - Nov-28-2017

1. Use python code tags over quote.

Sound like server isn't listen.
String isn't encode

example
import socket
import threading

def server(host, port):
    print("Enter Server")
    BUFFER_SIZE = 1024
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((host, port))
    server_socket.listen(1)

    c_sock, addr = server_socket.accept()
    data = c_sock.recv(BUFFER_SIZE)
    print("Server recieve", data.decode())


def client(host, port):
    print("Enter Client")
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    client_socket.connect((host, port))
    client_socket.send("Hello".encode())


def main():
    host = '0.0.0.0'
    port = 9012

    myserver = threading.Thread(target=server, args=(host, port))
    myserver.start()

    myclient = threading.Thread(target=client, args=(host, port))
    myclient.start()

    myserver.join()
    myclient.join()

if __name__ == '__main__':
    main()



RE: Socket - Keep Alive? - wavic - Nov-29-2017

Run it on the local host to try it. If it works check the router settings.