Python Forum
Thread Rating:
  • 2 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Socket - Keep Alive?
#1
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
Reply
#2
See https://python-forum.io/Thread-File-Transfer
Reply
#3
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()
99 percent of computer problems exists between chair and keyboard.
Reply
#4
Run it on the local host to try it. If it works check the router settings.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020