Socket Server refuses multiple connections with threading - python

I'm trying to do a multi-threaded python socket server, I created one thread that listens for connections and accepts them, within it I also creates sub-threads for each new connection.
PROBLEM: after a connection is established with one client , when another client tries to connect i get the following error in the client-side:
connectionrefusederror: [winerror 10061] no connection could be made because the target machine actively refused it >>> in multiclientgui
I didn't wanna try multiprocessing to create a process for listening only,
Is it something in my code? Or in the OS (windows 10)? or what would it be?
def serv():
""" the main thread for listening"""
global future ,soc ,add
while True:
s.listen(5)
soc,add =s.accept()
future =pool.submit(clientHandle,soc,add) #handling thread
print(" a new thread created to serve the client")
def clientHandle(socObj, address):
print("thread been called")
global client_data
client_data =pd.DataFrame(columns=['Location','lat','long','speed','ID','Time'])
client_sockets.append(socObj)
client_addr.append(address)
while True :
content=socObj.recv(1024)
if len(content)>0:
data=content.decode()
str(data)
print(data)

Related

conn.send('Hi'.encode()) BrokenPipeError: [Errno 32] Broken pipe (SOCKET)

hi i make model server client which works fine and i also create separate GUI which need to two input server IP and port it only check whether server is up or not. But when i run server and then run my GUI and enter server IP and port it display connected on GUI but on server side it throw this error. The Server Client working fine but integration of GUI with server throw below error on server side.
conn.send('Hi'.encode()) # send only takes string BrokenPipeError: [Errno 32] Broken pip
This is server Code:
from socket import *
# Importing all from thread
import threading
# Defining server address and port
host = 'localhost'
port = 52000
data = " "
# Creating socket object
sock = socket()
# Binding socket to a address. bind() takes tuple of host and port.
sock.bind((host, port))
# Listening at the address
sock.listen(5) # 5 denotes the number of clients can queue
def clientthread(conn):
# infinite loop so that function do not terminate and thread do not end.
while True:
# Sending message to connected client
conn.send('Hi'.encode('utf-8')) # send only takes string
data =conn.recv(1024)
print (data.decode())
while True:
# Accepting incoming connections
conn, addr = sock.accept()
# Creating new thread. Calling clientthread function for this function and passing conn as argument.
thread = threading.Thread(target=clientthread, args=(conn,))
thread.start()
conn.close()
sock.close()
This is part of Gui Code which cause problem:
def isOpen(self, ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ip, int(port)))
data=s.recv(1024)
if data== b'Hi':
print("connected")
return True
except:
print("not connected")
return False
def check_password(self):
self.isOpen('localhost', 52000)
Your problem is simple.
Your client connects to the server
The server is creating a new thread with an infinite loop
The server sends a simple message
The client receives the message
The client closes the connection by default (!!!), since you returned from its method (no more references)
The server tries to receive a message, then proceeds (Error lies here)
Since the connection has been closed by the client, the server cannot send nor receive the next message inside the loop, since it is infinite. That is the cause of the error! Also there is no error handling in case of closing the connection, nor a protocol for closing on each side.
If you need a function that checks whether the server is online or not, you should create a function, (but I'm sure a simple connect is enough), that works like a ping. Example:
Client function:
def isOpen(self, ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((str(ip), int(port)))
s.send("ping".encode('utf-8'))
return s.recv(1024).decode('utf-8') == "pong" # return whether the response match or not
except:
return False # cant connect
Server function:
def clientthread(conn):
while True:
msg = conn.recv(1024).decode('utf-8') #receiving a message
if msg == "ping":
conn.send("pong".encode('utf-8')) # sending the response
conn.close() # closing the connection on both sides
break # since we only need to check whether the server is online, we break
From your previous questions I can tell you have some problems understanding how TCP socket communication works. Please take a moment and read a few articles about how to communicate through sockets. If you don't need live communications (continous data stream, like a video, game server, etc), only login forms for example, please stick with well-known protocols, like HTTP. Creating your own reliable protocol might be a little complicated if you just got into socket programming.
You could use flask for an HTTP back-end.

Python Socket Auto Reconnect

I'm a beginner in Python. So I wanted to make if a server shuts down, disconnects, the client just keeps connecting until the server is opened again. I get this error:
File "C:\Users\Laurynas\Desktop\project\client.py", line 24, in reconnect server1.connect((HOST, PORT)) OSError: [WinError 10056] A connect request was made on an already connected socket
Current client.py code:
import socket
import time
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = socket.gethostbyname(socket.gethostname())
PORT = 8888
# Check at the first try
def connect():
try:
server.connect((HOST, PORT))
messages()
except ConnectionRefusedError:
print("reconnecting, please wait...")
time.sleep(0.1)
connect()
# Check at the second, third, etc.
def reconnect():
try:
server1.connect((HOST, PORT))
messages()
except ConnectionRefusedError:
print("reconnecting, please wait...")
time.sleep(0.1)
reconnect()
def messages():
while True:
try:
command = server.recv(1024).decode()
print(command)
except:
reconnect()
pass
connect()
With the exception of listening sockets that are used for many accepts, data sockets cannot be reconnected and reused. On the client side a new socket needs to be created for the new connection and on the server side a new accept needs to be made. The old sockets should also be closed to get them out of the kernel.
This poses a difficulty because a server won't automatically know which client is reconnecting and which higher level activity should be restarted. This has to be baked into the protocol you implement on top of the connection. In HTTP for instance, each GET/PUT/POST reidentifies itself so that the web server knows how to do that, perhaps using a cookie based session id.
Bottom line, you can't keep on calling server.connect to start it up again.

ConnectionAbortedError: [Errno 53] Software caused connection abort

i am trying to establish connections for multiple sockets using multi-threading
this is the code
import socket as sc
if __name__ == '__main__':
#setup()
ports = [10000, 10010, 10020, 10030]
init_sockets()
init_threads()
def init_sockets():
global host_ip
global sockets
host_ip = sc.gethostname()
sockets = []
for port in ports:
socket = sc.socket()
socket.bind((host_ip, port))
socket.listen()
sockets.append(socket)
def init_threads():
threads = [
threading.Thread(target= init_connection, args= [socket])
for socket in sockets
]
for thread in threads:
thread.start()
def init_connection(socket):
client, address = socket.accept()
while running the code this error appears
ConnectionAbortedError: [Errno 53] Software caused connection abort
the error occurs in thread.start() statement in function init_threads()
i don't know why this is happening, and would really appreciate any help. i am trying to run multiple socket connections in parallel, if it's impossible this way, i am open to recommendations
solved it!
the problem seemed to be that when the main thread (program it self) is terminated, all the objects that it created are deleted, including the socket objects.
so when the secondary threads (threads that the main program started), still running, try to reference these deleted objects the error occurs
the solution for me appeared to be adding an infinite while loop in the main method. preventing the main thread from being terminated

BlockingIOError when trying to connect socket

I am building a TCP Client in Python, that is supposed to try to connect to the server until a connection is established or the program is closed.
I define a timeout on a blocking socket, but after the first attempt to connect I receive
BlockingIOError: [Errno 114] Operation already in progress
Here is a little code example:
import socket
TCP_IP = '192.168.1.10'
TCP_PORT = 7
class TcpClient:
def __init__(self):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.settimeout(5)
def connect(self):
self.s.connect((TCP_IP, TCP_PORT))
if __name__ == "__main__":
client = TcpClient()
while True:
try:
client.connect()
except socket.timeout:
pass
If I understand the python documentation correctly, the timeout should occur when the connection attempt was not successful. That would mean that the socket is not trying to establish a connection anymore, but it seems like it still is.
I tried to close the socket, too, but then I would need to create a new socket for every new connection attempt. I cannot believe that this is the perfect solution.
I am open for any suggestions or help regarding this problem.
Thank you!

python socket server - listen even if client disconnects

This works fine
#!/usr/bin/python
import urllib
import socket
import os
s = socket.socket()
host = socket.gethostname()
port = 1514
s.bind((host, port))
s.listen(500)
c, addr = s.accept()
while True:
# Establish connection with client.
print 'Got connection from', addr
print c.recv(1024)
c.send('Recieved')
c.close()
raw_input()
But a few things:
When the client disconnects, the program closes. I want to make it so even if the client disconnects, the program will keep on listening for a new connection
How can I make it wait infinitely for a connection?
You can just put a while True loop on the outside and try/except for the connection closing inside. In other words, accept() can be called in a loop.
However, the "right" way to do this is usually with an asynchronous/event-driven approach as is implemented by Python Twisted. That way you can accept connections from multiple clients concurrently, rather than having to wait for one connection to close before accepting the next one.

Categories