Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Keeping a socket open or some other kind of listening/monitoring program

Status
Not open for further replies.

canflyguy

Technical User
Jul 25, 2018
100
0
0
CA
Hi all!

I'm a newbie to Python with my background being Fortan & Basic when I was a kid and then wrote an extensive Visual Basic program a few years ago which worked well. I'm now trying to tie a computer to several pieces of equipment that will sit there and collect information as it comes in. I managed to put together/find some code that I modified to work, however I found that either 1. It gets one data entry and then stops receiving as the connection gets closed once the data gets sent from one of the outside connections or 2. If left with no data being sent, times out after a while. I do get data from either piece of equipment (2 currently, but more to follow), but once again it only gets the one line of data that is being sent and closed by the sending equipment. Here's the attachments of code and the timeout that comes up if left with no response. Maybe someone can suggest what is required or if I need to work with another format or language to get this working.
Thanks!

import socket, sys

socket.setdefaulttimeout(150)
host = ''
port = 65432
socksize = 1024

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("Server started on port: %s" % port)
s.listen(1)
print("Now listening...n")
conn, addr = s.accept()

while True:
print ('New connection from %s:%d' % (addr[0], addr[1]))
data = conn.recv(socksize)
if not data:
break
elif data == 'killsrv':
conn.close()
sys.exit()
else:
print(data)


And if no data sent to it:

Server started on port: 65432
Now listening...n
Traceback (most recent call last):
File "C:/Users/Administrator/AppData/Local/Programs/Python/Python310/TESTSOCKET4.py", line 13, in <module>
conn, addr = s.accept()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\socket.py", line 293, in accept
fd, addr = self._accept()
TimeoutError: timed out

 
You got the error: TimeoutError: timed out
Have you tried what happens if you don't set the timeout ?
When not tried before, then try to comment out this:
# socket.setdefaulttimeout(150)
 
I didn't see the tmeout setting on the top of the program as I had originally copied the code and modified it. Thanks!! It seems to work now although it only runs to the bottom of the program and doesn't seem to keep getting the data as it comes in and printing to screen. Later once I can see the connection maintained, I'll do more with it. I see in the code where it's like:
if not data:
break
elif data == 'killsrv':
conn.close()
sys.exit()

I though about commenting some of that out, but still don't know if it will keep receiving new data? It almost seems like it needs a go to statement although in looking for that last night I saw there is no such thing. I also wondered before I keep chasing this and working with this base programming, does it allow for multiple connections so that I could have more that one unit sending info to this program and showing it to screen?

Thanks!
 
I found this code that supposedly works for MultiConnection Server:

import selectors
sel = selectors.DefaultSelector()
# ...
lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
lsock.bind((host, port))
lsock.listen()
print('listening on', (host, port))
lsock.setblocking(False)
sel.register(lsock, selectors.EVENT_READ, data=None)


I just tried this code and it doesn't run giving me the error:
Traceback (most recent call last):
File "C:/Users/Administrator/AppData/Local/Programs/Python/Python310/MULTISERVER.py", line 4, in <module>
lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
NameError: name 'socket' is not defined

 
Actualy found another example that is running. The only thing that concerns me about it is that because the equipment that connects to this server app closes it's connection everytime it sends data, the thread count keeps going up on each connection. It concerns me that eventually it would cap out or get to a very high thread count number and stop functioning. Any ideas?


import socket
import os
from _thread import *

ServerSocket = socket.socket()
host = '192.168.1.142'
port = 65432
ThreadCount = 0
try:
ServerSocket.bind((host, port))
except socket.error as e:
print(str(e))

print('Waitiing for a Connection..')
ServerSocket.listen(5)


def threaded_client(connection):
#connection.send(str.encode('Welcome to the Server'))
while True:
data = connection.recv(2048)
print (data)
reply = 'Server Says: ' + data.decode('utf-8')
if not data:
break
#connection.sendall(str.encode(reply))
connection.close()

while True:
Client, address = ServerSocket.accept()
print('Connected to: ' + address[0] + ':' + str(address[1]))
start_new_thread(threaded_client, (Client, ))
ThreadCount += 1
print('Thread Number: ' + str(ThreadCount))
ServerSocket.close()

 
Hi canflyguy,
Unfortunately python code without indentation is not readable. To post your code with proper formatting, please place it between the tags
[pre]
Code:
[/pre]
[pre]...[/pre]
[pre]
[/pre]
 
Code:
import socket
import os
from _thread import *

ServerSocket = socket.socket()
host = '192.168.1.142'
port = 65432
ThreadCount = 0
try:
    ServerSocket.bind((host, port))
except socket.error as e:
    print(str(e))

print('Waitiing for a Connection..')
ServerSocket.listen(5)


def threaded_client(connection):
    #connection.send(str.encode('Welcome to the Server'))
    while True:
        data = connection.recv(2048)
        print (data)
        reply = 'Server Says: ' + data.decode('utf-8')
        if not data:
            break
        #connection.sendall(str.encode(reply))
    connection.close()

while True:
    Client, address = ServerSocket.accept()
    print('Connected to: ' + address[0] + ':' + str(address[1]))
    start_new_thread(threaded_client, (Client, ))
    ThreadCount += 1
    print('Thread Number: ' + str(ThreadCount))
ServerSocket.close()

hmmm. Like that I take it.
 
The last posting above with the code did work in terms of connecting with the equipment, but it would close after getting one string of data. In speaking with someone recently about this, it was suggested that I need to use a "session" connection rather than a socket. That way it remains open in a listening status taking in whatever data that is presented. Does anyone have an example of the format I need to modify or replace the program above to maintain this listening connection?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top