I am creating a socket server in python
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind("127.0.0.1", 9001)
s.listen(5)
When a connect a Client using socket.connect() I am able to connect and close the client connection. But I am unable to close the server from ctrl+c or keyboard interrupt using s.shutdown(socket.SOL_RDWR)
Is there a way I can shutdown the python socket server using keyinterrupt or programmatically?
Update:
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.listen(5)
while True and s:
conn, addr = s.accept()
conn.recv(1024).decode()
conn.send("Test message from server".encode())
conn.close()
# Position 4 Signal Here
Update 2:
I did try to do this within the loop above in Position 4 "# Position 4 Signal Here". It did not work
import sys
import signal
def signal_handler(signal, frame):
sys.exit(1)
signal.signal(signal.SIGINT, signal_handler)
Update:
0$: This is windows 10 OS
Related
Using sockets, the below Python code opens a port and waits for a connection. Then, it sends a response when a connection is made.
import socket
ip = 127.0.0.1
port = 80
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((ip, port))
s.listen(1)
conn, addr = s.accept()
conn.send(response)
conn.close()
If a connection is not established within 10 seconds, I would like it to move on. Is there a way to define a timeout for s.accept()?
s.accept(timeout=10)
Maybe something like the above line?
Thanks in advance for your help!
to set a timeout for socket s before you connect listen do s.settimeout(10)
edit
I assume it works when listening
Use socket.settimeout:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)
timeout = False
while not timeout:
try:
(conn, addr) = s.accept()
except socket.timeout:
pass
else:
# your code
To make a 10 second timeout the default behavior for any socket, you can use
socket.setdefaulttimeout(10)
I am writing a simple python proxy with Python 3.8 on Windows 10
If I use socket.accept I cannot terminate the process from console neither of these work: ctrl+c, ctrl+z, ctrl+d, break, ctrl+break, only closing the terminal.
I found in the docs this PIP https://www.python.org/dev/peps/pep-0475/ that is about retrying system calls on interrupts. I believe this is the reason why I cannot terminate the app.
Can anyone tell me a best practice how to terminate an app with a blocking socket.accept
Thanks in advance
my code:
import socket
bind_ip = "127.0.0.1"
bind_port = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((bind_ip, bind_port))
server.listen(5)
print("[*] Listening on {}:{}".format(bind_ip, bind_port))
def handle_client(client_socket):
request = client_socket.recv(1024)
print("received: " + request.decode('ascii'))
client_socket.send("ACK".encode('ascii'))
client_socket.close()
while True:
client, addr = server.accept()
print("[*] accepted {}:{}".format(addr[0], addr[1]))
handle_client(client)
The socket might be in a TIME_WAIT state from the earlier trials & executions of your code.
You can use this flag to mitigate this, socket.SO_REUSEADDR
Under the Python Socket Documentation, you can set the flag like this.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
You can also look into setting a timeout for the socket!
I am currently programming a python socket server, which is working fine but with a big issue:
First here is the code
import socket
import threading
class ThreadedServer(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
self.sock.bind((self.host, self.port))
def listen(self):
self.sock.listen(6)
while True:
client, address = self.sock.accept()
client.settimeout(20)
threading.Thread(target=self.listenToClient, args=(client, address)).start()
def listenToClient(self, client, address):
size = 1024
while True:
try:
data = client.recv(size)
if data:
response = data
client.send(response)
print(response)
else:
raise
except:
client.close()
return False
if __name__ == "__main__":
while True:
port_num = input("Port: ")
try:
port_num = int(port_num)
break
except ValueError:
pass
ThreadedServer(ipaddress, port_num).listen()
The point is to have a socket server that can listen to multiple clients at the same time.
While i can connect to this socket with another python program, I am having an issue as soon as the socket.close() command came or the client program exits.
Segmentation fault (core dumped)
I assume the issue lies in the multithreading of the python code, however i am unfortunately not able to identify what i have to change to make it resistant to clients closing the socket or exiting the client program. Many stackoverflow answers are referring to C directly and not to python.
Any idea would be greatly appreciated
UPDATE:
rewriting the listen function to :
def listen(self):
# self.sock.listen(6)
while True:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
self.sock.listen(6)
client, address = self.sock.accept()
client.settimeout(20)
threading.Thread(target=self.listenToClient, args=(client, address)).start()
did not help unfortunately
UPDATE2:
running the process in a single thread works (meaning: i replace the threading.Thread line with just a call to the listenToClient function)
I can then connect with a client script, close the connection and open it again.
This code is not giving output it just makes the browser busy. Any idea why?
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect(('127.0.0.1', port))
print (s.recv(1024))
s.close
import socket
s=socket.socket()
host = socket.gethostname()
port = 12345
s.bind(('127.0.0.1', port))
s.listen(5)
while True:
c,addr = s.accept()
print ('Got connection from', addr)
c.send('Thank you for connecting')
c.close()
client program:
import socket
f=open("hello.txt","r").read()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 12345
s.connect(('127.0.0.1', port))
s.sendall(str.encode(f))
print (s.recv(1024).decode('ascii'))
s.close()
server program:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket successfully created")
port = 12345
s.bind(('', port))
print ("socket binded to %s" %(port))
f=open("hi.txt","r").read()
s.listen(5)
print ("socket is listening")
while True:
c, addr = s.accept()
print ('Got connection from', addr)
print (c.recv(1024).decode('ascii'))
c.sendall(str.encode(f))
c.close()
server output:
Socket successfully created
socket binded to 12345
socket is listening
Got connection from ('127.0.0.1', 51630)
helloooooo
client output:
hiiiii
Open the two programs in seperate shells.
Run server program first then client program.
Dont close the server program before running client program.
Create two files one for server and one for client.
Read the data from those files and send it.
While receiving the data decode it and print it.
You can send entire data from files or just a single line it depends on you.
To know more about reading,writing and creating files you can refer https://docs.python.org/release/3.6.5/tutorial/inputoutput.html#reading-and-writing-files
Let me know if it worked :)
I'm trying the following client and server chat program. Although I get an error whenever I try to run the server program, when the client program runs it stays on a blank screen not allowing me to type anything. I've tried running server first and running client first and I get the same results. I can't read the error from the server program because it flashes the error and closes the window. Here is my code:
server:
#server
import socket
import time
HOST = ''
PORT = 8065
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
client:
#client
import socket
import time
HOST = "localhost"
PORT = 8065
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((HOST,PORT))
s.sendall('Helloworld')
data = s.recv(1024)
s.close()
print 'Recieved', repr(data)
Im not an expert but I was able to make your examples work by changing the socket from datagram to stream connection, and then encoding message being sent because strings aren't supported (although this might not effect you since I think that change was made in Python 3...I'm not 100% sure).
I believe the main issue is that you're trying to listen() but SOCK_DGRAM (UDP) doesn't support listen(), you just bind and go from there, whereas SOCK_STREAM (TCP) uses connections.
If you're just trying to get the program going, use the below code, unless there is a specific reason you'd like to use SOCK_DGRAM.
The code is below:
client
#client
import socket
import time
HOST = "localhost"
PORT = 8065
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
test = 'Helloworld'
s.sendall(test.encode())
data = s.recv(1024)
s.close()
print 'Recieved', repr(data)
server
#server
import socket
import time
HOST = ''
PORT = 8065
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
print ('Connected by', addr)
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()