alexk_66
asked on
Server socket send query to client in python
from socket import *
from threading import Thread
import time
import psycopg2
import sys
def myquery1():
con = None
try:
con = psycopg2.connect(database='mydb', user='myuser')
cur = con.cursor()
cur.execute("SELECT * FROM users")
while True:
row = cur.fetchone()
if row == None:
break
qu = row[0], "|", row[1], "|", row[4]
return (qu)
except psycopg2.DatabaseError, e:
qu = 'Error %s' % e
return (qu)
sys.exit(1)
finally:
if con:
con.close()
def myquery2():
con = None
try:
con = psycopg2.connect(database='mydb', user='myuser')
cur = con.cursor()
cur.execute("SELECT * FROM users_list")
while True:
row = cur.fetchone()
if row == None:
break
qu = row[0], "|", row[1], "|", row[4]
return (qu)
except psycopg2.DatabaseError, e:
qu = 'Error %s' % e
return (qu)
sys.exit(1)
finally:
if con:
con.close()
def clientHandler():
conn, addr = s.accept()
print addr, "is Connected"
while True:
data = conn.recv(1024)
if data == "!Q":
conn.send("Disconnected")
break
if not data: break
if data == "!Q1":
conn.send (str(myquery1()))
if data == "!Q2":
conn.send (str(myquery1()))
HOST = ''
PORT = 5000
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
print "Server is running......"
for i in range(5):
Thread(target=clientHandler).start()
s.close()
The code is working but not as I wish.
I need when from my client send !Q1, !Q2 ...and so on, the server must execute query and send me result. In my case I got but only last line.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ok then change this
to this
qu = row[0], "|", row[1], "|", row[4]
to this
qu = "{0}|{1}|{2}".format(row[0], row[1],row[4])
ASKER
Thank you again. I have two more questions for this project:
1. How can I make script to run all the time and for more that 5 thread. Now when I run script and close ssh client socket is disconnected.
2. How can I send variable from client ex. !Q1 users and on server side replace with cur.execute("SELECT * FROM 'variable from client'")
1. How can I make script to run all the time and for more that 5 thread. Now when I run script and close ssh client socket is disconnected.
2. How can I send variable from client ex. !Q1 users and on server side replace with cur.execute("SELECT * FROM 'variable from client'")
ASKER
[(4, 'first name', 'last name')]
but I need result in this format
4|first name|last name