Connect sql server to Python3 - client-server - python

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

Related

Python - socket server that allows connections from other networks (Port Forwarding? UPnP?)

How can I create a socket server that allows connections from other networks?
Currently, my server is running on my IPv4 address. This works fine. However, the server cannot be connected to from other networks. I know you can do port forwarding to get this to work, but how can I make the script automatically do port forwarding?
Here is my server code:
import socket, pickle
from _thread import *
from serverside import Player, get_chest_tiles
from maps import maps
server = '10.0.0.187'
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((server, port))
except socket.error as e:
print(e)
s.listen()
print(f'Server started with address: {server}, on port: {port}\nWaiting for connections...')
players = []
zombies = [False]
current_map = maps['town']
chest_tiles = get_chest_tiles(current_map[0])
def threaded_client(conn, player):
players.append(Player())
conn.sendall(pickle.dumps([players[player], player]))
while True:
reply = []
players_reply = []
try:
data = pickle.loads(conn.recv(999999))
if type(data) == list:
if data[0] == 'UPDATE_ZOMBIES':
global zombies
zombies = data[1]
elif data[0] == 'UPDATE_MAP':
global current_map
current_map = data[1]
else:
players[player] = data
if not data:
break
else:
for p in range(len(players)):
if p < player or p > player:
players_reply.append(players[p])
reply = [players_reply, current_map, zombies, chest_tiles]
conn.sendall(pickle.dumps(reply))
except:
break
print('Lost connection')
players.pop(player)
conn.close()
currentPlayer = 0
while True:
conn, addr = s.accept()
print('Connected to:', addr)
start_new_thread(threaded_client, (conn, currentPlayer))
currentPlayer += 1

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

Socket stuck in loop

I am trying to make server and client (I am still learning) but the server is stuck in the while loop even after he received the "exit" from the client.
what am I doing wrong?
thank you
server
import socket
s = socket.socket()
s.bind(("0.0.0.0",5511))
s.listen(1)
c, addr = s.accept()
msg = c.recv(2048).decode()
while msg != "exit":
print(msg)
print("still connected")
msg = c.recv(2048).decode()
c.settimeout(5)
c.close()
s.close()
client
import socket
s = socket.socket()
s.connect(("127.0.0.1",5511))
msg = input("What send to the server: ")
while msg != "exit":
s.send(msg.encode())
msg = input("What send to the server: ")
s.close()
I initially posted this as a edit to rmh's answer but the edit didn't go throug till now so I post my own answer
server.py
import socket
s = socket.socket()
s.connect(("127.0.0.1",5511))
msg = ""
while msg != "exit":
msg = input("What send to the server: ")
s.send(msg.encode())
s.close()
client.py
import socket
s = socket.socket()
s.bind(("0.0.0.0",5511))
s.listen(1)
c, addr = s.accept()
msg = c.recv(2048).decode()
while msg != "exit":
print(msg)
print("still connected")
msg = c.recv(2048).decode()
c.settimeout(5)
c.close()
s.close()
Thank you for all your help,
I added new line of "s.send(msg.encode())" after the "while" and it work now.
Thank you very much!
Take a look at your while loop in the client. It doesn't execute the body if msg == "exit". So if msg is "exit", the client doesn't send anything to the server. As a result, the server doesn't receive a message and blocks on the msg = c.recv(2048).decode() line in the ""server"" code.
server.py
import socket
s = socket.socket()
s.connect(("127.0.0.1",5511))
msg = ""
while msg != "exit":
msg = input("What send to the server: ")
s.send(msg.encode())
s.close()
client.py
import socket
s = socket.socket()
s.bind(("0.0.0.0",5511))
s.listen(1)
c, addr = s.accept()
msg = c.recv(2048).decode()
while msg != "exit":
print(msg)
print("still connected")
msg = c.recv(2048).decode()
c.settimeout(5)
c.close()
s.close()

Python server instant disconnect

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.

Python network/socket programming, simple game

Im trying to make a simple game but cant understand how to make it work and send more then one thing over the network. It works the first time but it supposed to go 10 times. It only sends 1 random number now but i want it to send one new when the game goes again and want a new number.
Server
import socket, random
sock = socket.socket()
host = socket.gethostname()
port = 12345
sock.bind((host, port))
sock.listen(5)
c, addr = sock.accept()
cpu = random.choice(range(0, 3))
c.send(cpu)
gameon = c.recv(int(1024))
Client
import socket, random
sock = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
sock.connect((host, port))
GAMEON = 'Rock', 'Paper', 'Scissors'
game = 0
iwin = 0
ilose = 0
tie = 0
while game < 10:
for i in range(0, 3):
print "%d %s" % (i + 1, GAMEON[i])
player = int(input ("Choose from 1-3: ")) - 1
cpu = int(sock.recv(1024))
print cpu
print""
print "%s vs %s" % (GAMEON[player], GAMEON[cpu])
print ""
if cpu != player:
if (player - cpu) % 3 < (cpu - player) % 3:
print "Player wins\n"
iwin += 1
else:
print "CPU wins\n"
ilose += 1
else:
print "TIE!\n"
tie += 1
game += 1
sock.send(str(game))
print"Game is done"
print"you win: ", (iwin), "Times"
print"computer wins: ", (ilose), "Times"
print"tie: ", (tie), "Times"
The problem is that your server will serve one request and then stop. You need to put it in some kind of while loop.
I wrote a basic IM server/client in Python which might help you: https://github.com/hdgarrood/PyMess/blob/master/server/basictcpserver.py#L59
You need threads to do your bidding.
Example code
# Listen
s.listen(10)
print 'Socket now listening on port ' + str(PORT) + "..."
while 1:
# wait
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ":" + str(addr[1])
# Let's fork a thread for each request
processThread = threading.Thread(target=processConnection, args=(conn, addr[0]));
processThread.start()
s.close()
Your processConnection will look like this:
# Process Connection
def processConnection(conn, ip):
print "Thread started..."
print "-------------------------------------------------------------";
cpu = random.choice(range(0, 3))
conn.send(cpu)
gameon = conn.recv(int(1024))
conn.close()
Update 1
If you need the server to keep talking with the client, then do this. Server will wait for the client to send back a message. If client sends anything, server will return a random number. If the client doesn't need anymore data, just close the connection and server loop will end.
import socket, random
sock = socket.socket()
host = socket.gethostname()
port = 12345
sock.bind((host, port))
sock.listen(5)
c, addr = sock.accept()
white True:
cpu = random.choice(range(0, 3))
c.send(cpu)
gameon = c.recv(int(1024))
if gameon is None:
break

Categories