I have the below python script(server.py) in order to listen to a port and capture the requests from the client. I am calling this script from another python file(Main.py). My requirement is to stop executing server.py after certain amount of time. I tried using exit() at the last line of the file - server.py to stop the server and stop the execution of the file, however I was not able to stop the script from running and the server kept responding. Can anyone help me in letting me know where I am going wrong.
Server.py
bind_ip = "127.0.0.1"
bind_port = 2530
def servercreate():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip,bind_port))
server.listen(5)
while True:
client, addr = server.accept()
print('[*] Accepted connection from: %s:%d' % (addr[0], addr[1]))
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()
def handle_client(client_socket):
request = client_socket.recv(2056)
print('[*] Received: %s' % request)
message = "{}"
client_socket.send(message.encode('utf-8'))
client_socket.close()
if __name__ == '__main__':
servercreate()
Main.py
import Server
Server.servercreate()
if you don't want your code interrupted by time.sleep (which I think stops the code from running), use this:
import time
timeout = time.time() + 10
while True:
print ('hello')
if time.time() > timeout:
print ('program terminated')
break
if you want 10 minutes worth of time use:
timeout = time.time() + 60*10
If you just want to stop the program running after a certain amount of time use something like
import time
x=0
while True:
print ('waiting 5')
time.sleep(5)
x += 1
if x == (10):
break
the time.sleep is in seconds, break stops the loop and should end your program
update, try this:
import time
bind_ip = "127.0.0.1"
bind_port = 2530
def servercreate():
#put minutes of time you want program to run for below
minutes = 10
timeout = time.time() + (60*minutes)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip,bind_port))
server.listen(5)
while True:
client, addr = server.accept()
print('[*] Accepted connection from: %s:%d' % (addr[0], addr[1]))
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()
if time.time() > timeout:
break
def handle_client(client_socket):
request = client_socket.recv(2056)
print('[*] Received: %s' % request)
message = "{}"
client_socket.send(message.encode('utf-8'))
client_socket.close()
if __name__ == '__main__':
servercreate()
Related
this is for server authentication for my application.
(im working on login function so dont mind about it)
what i wanna do is to make server receive heartbeat from client
and close client socket if its doesnt respond in a few min
also i want to detect number of connections per user.
for receiving heartbeat, i can make the client send heartbeat constantly but
how do you make the server decect it? i know time measurement is needed but
if i put time.perf_counter() right before 'client_socket.recv(1024)' the counter function wont be executed because its waiting on receiving. so how would i solve this?
and im also trying to make it detect number of connections per user. (5 maximum connections per user) for detection, i give username + 1 when a user is connected and give -1 when the user disconnects but im not sure if the method im doing is correct or a good way to do so.
i'd be appreciated if you could help me out
------------------------server----------------------------
import socket
from _thread import *
import sys
import time
username = ['test123', 'hongengi']
userconnect= 0
def threaded(client_socket, addr):
print('Connected by :', addr[0], ':', addr[1])
while True:
try:
data = client_socket.recv(1024)
print (data.decode())
print('Received from ' + addr[0],':',addr[1] , data.decode())
if data.decode() == ".": # heartbeat
heartbeat = time.perf_counter()
print ("heartbeat")
if data.decode() == "test123":
print ("login success")
userconnect == userconnect + 1
if not data:
print ("no data / disconnect ")
print('Disconnected by ' + addr[0],':',addr[1])
userconnect == userconnect - 1
break
client_socket.send(data)
except (ConnectionResetError, socket.error) as e:
print ("error occurs")
print('Disconnected by ' + addr[0],':',addr[1])
userconnect == userconnect - 1
break
client_socket.close()
HOST = '127.0.0.1'
PORT = 5000
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen()
print('server start')
while True:
print('wait')
client_socket, addr = server_socket.accept()
start_new_thread(threaded, (client_socket, addr))
server_socket.close()
------------------------client----------------------------
import socket
SERVER_IP = 'localhost'
SERVER_PORT = 5000
SIZE = 100
SERVER_ADDR = (SERVER_IP, SERVER_PORT)
heartbeat = "."
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(SERVER_ADDR)
#username = "test123"
#userpass = "123123"
while True:
client_socket.send(heartbeat.encode())
msg = client_socket.recv(SIZE)
print (msg.decode())
One end of a socket is never "notified" when the other socket closes. There is no direct connection, so the only way to tell this is to time out. You can use socket.timeout to establish a timeout time. Your recv will then return with 0 bytes, and that's an indication that your timeout expired.
How to set timeout on python's socket recv method?
I am trying to check if data is available on one port. If this it is avaiable then a message "yes" should be sent to another port and "no" if there is no data.
A client is connecting to that port where "yes" or "no" is coming. I run the script and every thing looked fine. But after one hour I got the error:
Runtime error can not start new thread. Exception in Thread 11:
Traceback< most recent call last: file threading.py line 914 in boot strap-inner.
I am new to python and I really do not understand what is going on. My code contains many threads as I am checking data from 10 ports and sending "yes" or "no" message to other 10 ports.
Here is a part of my code for 1 port:
import time
import socket
import threading
from threading import Thread
import select
#-----------------------------------Server --------------------------
s = socket.socket(socket.AF_INET) #Socket
h = '127.0.0.1' #Host where data coming from
p = 14201 #Port
halarm = "127.0.0.1" # A port will be opened to send availabilty status
palarm = 14202 # Port
def Server ():
while True:
try:
time.sleep(0.1)
s.connect((h, p))
except socket.error:
pass
#-----------------------------------Server/Client -------------------------------
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind((halarm, palarm)) # Bind to the Port where
sock.listen(1)
def func(conn): # Server-Client Function
while True:
try:
global s
Timeout = select.select([s], [], [], 5)# Timeout in seconds
connected = True
while True:
try:
if Timeout[0]:
conn.send(bytes("yes", "utf-8"))
time.sleep(3)
else:
conn.send(bytes("no", "utf-8"))
time.sleep(3)
newConnection= False
while not newConnection:
try:
s = socket.socket(socket.AF_INET)
s.connect((h, p))
Timeout = select.select([s], [], [], 5)# Timeout in seconds
newConnection= True
except socket.error:
conn.send(bytes("Port is closed", "utf-8"))
time.sleep(3)
pass
except socket.error:
pass
except:
pass
def connThread():
while True:
conn, addr = sock.accept()
time.sleep(0.1)
Thread(target = func, args=(conn,)).start()
if __name__ == '__main__':
Thread(target = Server).start()
Thread(target = connThread).start()
How can I solve this problem ? I appreciate all your help.
I am trying to set up a tcp server in Python using Multithreading. The problem is that the queue only return data from only one thread. That means it only prints the data from the thread created with 5555 or 5556. I confirmed both data reaches port by connecting one device per time but it does not print the result from connection to the other port when more than one device connected.
Thanks for your help.
#!usr/bin/python
from threading import Thread
import socket
import sys
from queue import Queue
def clientthread(conn,q):
buffer=""
data = conn.recv(8192)
buffer=data
q.put(buffer)
return buffer
def main():
try:
host = '169.254.162.144'
port = 5555
tot_socket =2
list_sock = []
conarr=[]
threads=[]
for i in range(tot_socket):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host, port+i))
s.listen(10)
list_sock.append(s)
print ("[*] Server listening on %s %d" %(host, (port+i)))
for j in range(len(list_sock)):
conn, addr = list_sock[j].accept()
conarr.append(conn)
print('[*] Connected with ' + addr[0] + ':' + str(addr[1]))
while 1:
queue1 = Queue()
for j in range(len(list_sock)):
thread =Thread( target=clientthread, args=(conn, queue1) )
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
while not queue1.empty():
result = queue1.get()
print(result)
threads=[]
s.close()
except KeyboardInterrupt as msg:
sys.exit(0)
if __name__ == "__main__":
main()
I have written a python program in which I created a UDP listener in thread 1 and trying to do something in thread 2. The issue here is control is stuck up in thread 1 and it never returns to main thread so thread 2 is not even starting up.
import threading
import socket
import time
data = ''
def ListenerUDP():
sock1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address1 = ('localhost', 5000)
print('starting up UDP server on %s port %s' % server_address1)
sock1.bind(server_address1)
while True:
print('\nUDP server is now listening up')
data, address = sock1.recvfrom(4096)
print('received %s bytes from %s' % (len(data), address))
print('is %s' % data.hex())
def Forwarder():
print('do something')
print('Starting main thread')
t1 = threading.Thread(target=ListenerUDP)
t1.start()
t2 = threading.Thread(target=Forwarder)
t2.start()
can someone please help fixing it.
I am writing a script for handling HTTP request through socket programming. My Python Script just reads each HTTP response, search for few keywords and increment the counters.
Only starting the script takes CPU upto 90-99% when there is no incoming messages. How should i handle this?
HOST = ''
SOCKET_LIST = []
RECV_BUFFER = 40966
PORT=int(sys.argv[1])
serviceInitiatedEvent=0
deliveredEvent=0
EstablishedEvent=0
ConnectionClearedEvent=0
def chat_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
SOCKET_LIST.append(server_socket)
print "Chat server started on port " + str(PORT)
try:
while 1:
ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[],0)
for sock in ready_to_read:
if sock == server_socket:
sockfd, addr = server_socket.accept()
SOCKET_LIST.append(sockfd)
else:
try:
data = sock.recv(RECV_BUFFER)
if data:
if re.search('serviceInitiatedEvent></SOAP-ENV',data):
global serviceInitiatedEvent
serviceInitiatedEvent+=1
if re.search('deliveredEvent></SOAP-ENV',data):
global deliveredEvent
deliveredEvent+=1
else:
if sock in SOCKET_LIST:
SOCKET_LIST.remove(sock)
except:
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
continue
except KeyboardInterrupt:
print "service Initiated Event:%s" % (serviceInitiatedEvent)
print "delivered Event: %s" % (deliveredEvent)
server_socket.close()
if __name__ == "__main__":
sys.exit(chat_server())
If you have code with while 1 loop utilizing 100%, that's probably the culprit. It's called busy waiting.
select function has timeout parameter that specifies how long it should wait for events. In your code, you set it to 0, so that when there is no data available in sockets, control returns immediately, causing busy waiting loop.
Specify some larger timeout, based on your needs, so that your code won't spin when there's nothing to do:
ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[], 1)
# ^^^ here