Python server instant disconnect - python

Here's the code giving me the issue:
def connect():
s.listen(2)
print("Server listening")
conn,addr=s.accept()
print("Connected with " + str(addr) + '\n')
recv()
def recv():
while 1:
try:
print("Starting try statement")
data=conn.recv(1024)
if data == "":
print("No data")
recv()
else:
print("Data")
print(data.decode('UTF-8') + " -END")
recv()
except:
print("No connection")
connect()
conn.close()
When I execute the code, it'll connect to the client and be ready to receive a message at any point. However, once it's executed this is what appears.
Server listening
Connected with ('xx.xxx.xxx.xx', xxxxx)
Starting try statement
No connection
Server listening
IP censored. Does anyone have a fix for this?
EDIT: Typo
CLIENT CODE (From TKinter GUI)
s.connect((host,port))
self.chatlog['state'] = NORMAL
self.chatlog.insert(END, ("===CONNECTED TO SERVER\n"))
self.chatlog['state'] = DISABLED
self.chatlog.yview(END)
self.conn=True
print("Connected")

You are doing it wrong.
Ya 'now that local conn what you are creating in function connect is not accessible from function recv? That is a reason for not reciving anything.
My solution using that code, without using classes and threads but with select and sys module is:
import sys
import select
def connect()
s.listen(2)
print('Sever listening')
inputs = [s, sys.stdin]
running = 1
while running:
i_rdy = select.select(inputs,[],[],1)[0]
if s in i_rdy:
conn, addr = s.accept()
print ('Connected with ' + str(addr) + '\n')
recv(conn)
if sys.stdin in i_rdy:
junk = std.stdin.readline()
if junk.lstrip('\n') == 'exit':
running = 0
print('Closing server')
s.close()
def recv(conn):
while 1:
try:
print("Starting try statement")
data = conn.recv(1024)
if data == "":
print("No data")
else:
print("Data")
print(data.decode('UTF-8') + " -END")
except:
print("No connection")
#traceback
print(sys.exc_info)
break
try:
conn.close()
except:
pass
As you can see can "exit" when u type exit to console but only when there is no active connection...
That why you should consider rewrite this to classes, it would be a lot easier to stop, not "ugly" and it could handle multiple connections.

Related

OSError: [WinError 10022] An invalid argument was supplied. Process finished with exit code 1

I was following a tutorial and got stuck here. When I ran the same code for the first time, It went well. But from the second time, it shows error in the same code. I restarted my computer and then it ran once and from the second time, it again shows error.
#THE CODE:
import socket
from _thread import *
import sys
server = "192.168.0.102"
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((server, port))
except socket.error as e:
str(e)
s.listen(2)
print("Waiting for a connection , Server Started")
def read_pos(str):
str = str.split(",")
return int(str[0]), int(str[1])
def make_pos(tup):
return str(tup[0]) + "," + str(tup[1])
pos = [(0, 0), (100, 100)]
def threaded_client(conn, player):
conn.send(str.encode(make_pos(pos[player])))
reply = ""
while True:
try:
data = read_pos(conn.recv(2048).decode())
pos[player] = data
if not data:
print("Disconnected")
break
else:
if player == 1:
reply = pos[0]
else:
reply = pos[1]
print("Received : ", data)
print("Sending: ", reply)
conn.sendall(str.encode(make_pos(reply)))
except:
break
print("Lost Connection")
conn.close()
currentPlayer = 0
while True:
conn, addr = s.accept()
print("Connected to : ", addr)
start_new_thread(threaded_client, (conn, currentPlayer))
currentPlayer += 1
Try using a different IP address. The code worked correctly when I used 127.0.0.1 which is the local machine.
server = "127.0.0.1"
port = 5555

Connect sql server to Python3 - client-server

i'm new in socket programming with python i wrote some code for client and server that is not completed.
i want to connect my server side to Sql server dbms to store data there (this is a student management system) i want to send some data from client side then server side store them on data base and when got asked by client return them.
Here is my both side codes:
this is client:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host ="127.0.0.1"
port =8000
def send(message):
message=str(message)
s.send(message.encode())
data = s.recv(1024).decode()
print (data)
def end():
s.close ()
def menu1():
print("Data has been saved to DB!\nWhat you need next?\n1.Close Connection.\n2.Enter More Data.\n3.Get Data.")
while 1:
m=input()
if int(m)==1:
end()
elif int(m)==2:
enter_data()
elif int(m)==3:
get_data()
else:
print("Choose a Num between 1-3!\n")
def enter_data():
flag=0
while 1:
if flag==0:
r = input('enter amount of student: ')
for i in range (0,int(r)):
name=input("Enter Student %d name"%(i))
send(name)
break
menu1()
def start():
s.connect((host,port))
print("You are connected to server!")
print("1.Enter Data")
print("2.Get Data")
m=input()
if int(m)==1:
enter_data()
elif int(m)==2:
end()
def menu():
m = input("press any key to connect!\n");
start()
if __name__ == "__main__":
menu()
and this is server side code:
import socket
from threading import *
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 8000
#print (host)
#print (port)
serversocket.bind((host, port))
class client(Thread):
def __init__(self, socket, address):
Thread.__init__(self)
self.sock = socket
self.addr = address
self.start()
def run(self):
#amount=self.sock.recv(1024).decode()
#amount=int(amount)
#counter=0
while 1:
api=self.sock.recv(1024).decode()
#print(self.sock.recv(1024).decode())
print("Client sent some messages: %s"%(api))
#api=self.sock.recv(1024).decode()
if str(api)=="avarage":
avarage=2/10
c=str(avarage)
self.sock.send(c.encode())
else:
avarage = 3 / 10
c = str(avarage)
self.sock.send(c.encode())
serversocket.listen(5)
print ("server started and listening to port:%s"%(port))
while 1:
clientsocket, address = serversocket.accept()
client(clientsocket, address)
I'm a bit new in this type of programming so please give me a part of code that i need to add.
thanks in advance.
I know that some parts of this code is not usable i just wrote them for test some things and get the concept of that.
also when i want to close connection server side i got this error:
File "C:/Users/name/PycharmProjects/Socket/venv/Socket1.py", line 23, in run
api=self.sock.recv(1024).decode()
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

What is the problem with the following python socket server code?

Why is it that the following server code cannot seem to accept new connections with clients even after the first connection is closed?
def bindPort(port):
global return_response
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
serverSocket.bind(('', port))
except:
print("Cannot bind to port. Error: " + str(sys.exc_info))
serverSocket.listen(2)
print("The server is ready to receive")
count = 0
while True:
connectionSocket, addr = serverSocket.accept()
count += 1
print("Accepted {} connections so far.".format(count))
print('Connection established from {}'.format(addr))
while True:
sentence = connectionSocket.recv(1024)
if not sentence:
print("Empty")
break
print(sentence)
#parseIncomingRequest(sentence.decode())
print(return_response)
connectionSocket.send(return_response.encode())
return_response = ''
print("Closing loop")
connectionSocket.close()
I apologize for not reading the question properly
1)declare the return response variable before you use it
2)break out of the second while loop if you want accept an other connection .In the question you said that no connections were being accepted after the socket was closed but for the socket to close you have to break out out of the second while loop.or in my opinion you should remove the second loop .
3)if you want to keep listening on the socket and still be able to receive other connections use the threading module
def bindPort(port):
global return_response
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
serverSocket.bind(('', port))
except:
print("Cannot bind to port. Error: " + str(sys.exc_info))
serverSocket.listen(2)
print("The server is ready to receive")
count = 0
while True:
connectionSocket, addr = serverSocket.accept()
count += 1
print("Accepted {} connections so far.".format(count))
print('Connection established from {}'.format(addr))
sentence = connectionSocket.recv(1024)
if not sentence:
print("Empty")
break
print(sentence)
#parseIncomingRequest(sentence.decode())
return_response = ''
print(return_response)
connectionSocket.send(return_response.encode())
connectionSocket.shutdown(socket.SHUT_RDWR)
connectionSocket.close()
4)or if you want to keep the loop for further modfication
import socket
def bindPort(port):
global return_response
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
serverSocket.bind(('', port))
except:
print("Cannot bind to port. Error: " + str(sys.exc_info))
serverSocket.listen(2)
print("The server is ready to receive")
count = 0
while True:
connectionSocket, addr = serverSocket.accept()
count += 1
print("Accepted {} connections so far.".format(count))
print('Connection established from {}'.format(addr))
while True:
sentence = connectionSocket.recv(1024)
if not sentence:
print("Empty")
break
print(sentence)
#parseIncomingRequest(sentence.decode())
return_response = 'a'
print(return_response)
connectionSocket.send(return_response.encode())
break
print("Closing loop")
connectionSocket.shutdown(socket.SHUT_RDWR)
connectionSocket.close()

Client doesn't connect to server from different computer on the INTERNET

I have been working on a very simple group chat program. The program works well when tested on the same computer, but doesn't work between different computers on the INTERNET.
I have tried disabling Windows Fire Wall.
I cannot narrow down the code, Sorry.
The program uses a socket and Threading library.
Client Code:
import socket
import threading
SERVER_IP = "127.0.0.1" #This is changed to the servers PUBLIC IP when testing with another computer.
SERVER_PORT = 9279
global name
global sock
def connect():
global sock
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_addres = (SERVER_IP, SERVER_PORT)
try:
sock.connect(server_addres)
print("Connected.")
return 1
except:
print("Cant connect to server.")
return 0
def send_msg():
global sock
while True:
try:
msg = name + " >> " + input()
sock.sendall(msg.encode())
except Exception as e:
print(e)
def recieve_msg():
global sock
server_active = 1
while True and server_active:
try:
recieved_msg = sock.recv(1024).decode()
print("\n" + recieved_msg)
except Exception as e:
print(e)
server_active = 0
def main():
global name
name = input("Enter name: ")
connected = connect()
while True and connected:
send_thread = threading.Thread(target=send_msg)
send_thread.start()
recv_thread = threading.Thread(target=recieve_msg)
recv_thread.start()
while recv_thread.is_alive():
recv_thread.join(timeout=0.1)
sock.close()
Server code:
import socket
import _thread
host = "My private IP"
port = 9279
global thread_active
thread_active = 1
global client_list
client_list = []
global addr
def on_new_client(clientsocket, pt):
global thread_active
global client_list
while True and thread_active:
global addr
try:
msg = clientsocket.recv(1024).decode()
print(msg + " " + str(addr))
for client in client_list:
client.send(msg.encode())
except Exception as e:
print("Client " + str(addr[0]) + ':' + str(addr[1]) + " disconnected (" + str(e) + ")")
if clientsocket in client_list:
client_list.remove(clientsocket)
print(client_list)
thread_active = 0
s = socket.socket()
print('Server started!')
print('Waiting for clients...')
s.bind((host, port)) # Bind to the port
s.listen(10) # Now wait for client connection.
while True:
c, addr = s.accept()
print('Got connection from', addr)
client_list.append(c)
_thread.start_new_thread(on_new_client, (c, 0))
thread_active = 1
s.close()
clientsocket.close()

Python script stuck at queue.join()

I am trying to implement a server for handling many clients (from thenewboston python reverse shell tutorials). I have the exact same code but when i run the script it gets stuck at queue.join(). How to make it work? I am unable to figure it out.
Here is the code
import socket
import sys
import threading
from queue import Queue
NUMBER_OF_THREADS = 2
JOB_NUMBER = [1, 2]
queue = Queue()
all_connections = []
all_addresses = []
# thread 1
# create socket (allows two computers to connect)
def socket_create():
try:
global host # ip address of the server
global port # port is to identify the kind of data
global s
host = ''
port = 9999
s = socket.socket()
except socket.error as msg:
print("Socket creation error: " + str(msg))
return
# bind socket to port and wait for connection from client
def socket_bind():
try:
global host
global port
global s
print("Binding socket to port: " + str(port))
s.bind((host, port))
s.listen(5)
# 5 is the no. of conections that can be made before server starts rejecting other requests
except socket.error as msg:
print("Socket binding error: " + str(msg) + "\n" + "Retrying...")
socket_bind()
return
# accept connections from multiple clients and save to list
def accept_connections():
for c in all_connections:
c.close()
del all_connections[:]
del all_addresses[:]
while 1:
try:
conn, address = s.accept()
conn.setblocking(1)
all_connections.append(conn)
all_addresses.append(address)
print("\nConnection has been establish: " + address[0])
except:
print("Error accepting connections")
return
# thread 2
# custom command promt for sending commands remotely
def start_turtle():
while True:
cmd = input('turtle> ')
if cmd == 'list':
list_connections()
elif 'select' in cmd:
conn = get_target(cmd)
if conn is not None:
send_target_commands(conn)
else:
print("Command not recognized")
return
# listing all the connections with indexing in the custom promt
def list_connections():
results = ''
for i, conn in enumerate(all_connections):
try:
conn.send(str.encode(' '))
conn.recv(20480)
except:
del all_connections[i]
del all_addresses[i]
continue
results += str(i) + ' ' + str(all_addresses[i][0]) + ' ' + str(all_addresses[i][1]) + '\n'
print('-----Clients-----' + '\n' + results)
return
# select a target client
def get_target(cmd):
try:
target = cmd.replace('select ', '')
target = int(target)
conn = all_connections[target]
print("You are now connected to " + str(all_addresses[target][0]))
print(str(all_addresses[target][0]) + '> ', end="")
return conn
except:
print("Not a valid selection")
return None
return
# connect with remote target client
def send_target_commands(conn):
while True:
try:
cmd = input()
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_response = str(conn.recv(20480), "utf-8")
print(client_response, end="")
if cmd == "quit":
break
except:
print("Connection was lost")
break
return
# create worker threads
def create_workers():
for _ in range(NUMBER_OF_THREADS):
t = threading.Thread(target=work)
t.daemon = True
t.start
return
# do the next job in the queue (one handles connections, other sends commands)
def work():
while True:
x = queue.get()
if x == 1:
socket_create()
socket_bind()
accept_connections()
if x == 2:
start_turtle()
queue.task_done()
return
# create jobs for later extracting them and assigning them to the threads
def create_jobs():
for x in JOB_NUMBER:
queue.put(x)
queue.join()
return
def main():
create_workers()
create_jobs()
if __name__ == '__main__':
main()
Since you are using infinite loops (while True) at start_turtle and (while 1) at accept_connections they are not returning.
Since they don't return the func work never calls queue.task_done(), so the queue stuck joining.
I'm afraid you need to do one of the following:
start both start_turtle and accept_connections in parallel processes or threads.
Be sure they should call the queue.task_done().
For instance, you may include the queue as parameter and call it before starting the infinite loops (second option).
def work():
while True:
x = queue.get()
if x == 1:
socket_create()
socket_bind()
accept_connections(queue) # call queue.task_done() there
if x == 2:
start_turtle(queue) # call queue.task_done() in start_turtle
return
def start_turtle(queue):
queue.task_done() # Join one item from the queue
while True:
cmd = input('turtle> ')
if cmd == 'list':
list_connections()
elif 'select' in cmd:
conn = get_target(cmd)
if conn is not None:
send_target_commands(conn)
else:
print("Command not recognized")
return
On the other hand, in your create_workers you don't call the start method of the thread so your workers didn't really start.
Perhaps this is a typo.
def create_workers():
for _ in range(NUMBER_OF_THREADS):
t = threading.Thread(target=work)
t.daemon = True
# t.start # Not starting the Thread
t.start() # You need to call the start method
return

Categories