×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

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

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

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

(OP)
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

Replies continue below

Recommended for you

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

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)

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

(OP)
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!

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

(OP)
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

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

(OP)
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()

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

Hi canflyguy,
Unfortunately python code without indentation is not readable. To post your code with proper formatting, please place it between the tags
[code] 
... 
[/code] 

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

(OP)

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.

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

(OP)
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?

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login


Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close