I am learning how to create multithreaded socket server in Python. I used example from some site that I don't remember. I am trying to create simple plugin system but I am not successful. It says that I am passing 3 arguments instead of 2. This is my code:
def handler(clientsock,addr):
while 1:
data = clientsock.recv(BUFF)
if not data: break
data_sanitized = data.rstrip()
print repr(addr) + ' received: ' + repr(data_sanitized)
from plugins.helloWorld import helloWorld
clazz.fireIt(clientsock,data)#HERE IS THE PROBLEM I THINK
if "close" == data.rstrip(): break
clientsock.close()
print addr, "CLIENT CLOSED CONNECTION"
if __name__=='__main__':
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serversock.bind(ADDR)
print 'STARTED SERVER, WAITING FOR CONNECTIONS', PORT
serversock.listen(5)
while 1:
clientsock, addr = serversock.accept()
print 'INCOMING CONNECTION FROM: ', addr
thread.start_new_thread(handler, (clientsock, adde))
and this is my plugin:
from socket import *
def response(key):
return '<response>' + key + '</response>'
class helloWorld():
def fireIt(clientsock,data):
print clientsock
clientsock.send(response(data))
print 'SENDING: ' + repr(response(data))
Thank you
Related
I am sending a string from a python client to a python socket server
here is the server side code where i am printing the received value :
def threaded_client(connection):
while True:
data = connection.recv(2048)
print(data)
datatemp = data.decode('utf-8')
print(datatemp)
message = datatemp.split('_')
print(message[0])
while True:
Client, address = ServerSocket.accept()
print('Connected to: ' + address[0] + ':' + str(address[1]))
start_new_thread(threaded_client, (Client, ))
ServerSocket.close()
and on the server side i am printing print(data) , print(datatemp) and lit('_') but non of these print statements is printing anything
What am i doing wrong ?
UPDATE 1:
I am using these Imports:
import socket
import os
from _thread import *
Here is the full server code :
import socket
import os
from _thread import *
ServerSocket = socket.socket()
host = '127.0.0.1'
port = 34534
ThreadCount = 0
try:
ServerSocket.bind((host, port))
except socket.error as e:
print(str(e))
print('Waitiing for a Connection..')
ServerSocket.listen(5)
def threaded_client(connection):
while True:
data = connection.recv(2048)
print(data)
datatemp = data.decode('utf-8')
print(datatemp)
message = datatemp.split('_')
print(message[0])
while True:
Client, address = ServerSocket.accept()
print('Connected to: ' + address[0] + ':' + str(address[1]))
start_new_thread(threaded_client, (Client, ))
ServerSocket.close()
I am making server-client communication in python using sockets and threading module. I connect client to server, send some data, receive some data, but the problem is, I can send only two messages. After those, the server is not reciving my packets. Can someone tell me what's wrong? Thanks in advance.
Server.py:
import socket
from threading import Thread
class Server:
def __init__(self):
self.host = '127.0.0.1'
self.port = 9999
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((self.host, self.port))
self.server.listen(5)
self.threads = []
self.listen_for_clients()
def listen_for_clients(self):
print('Listening...')
while True:
client, addr = self.server.accept()
print('Accepted Connection from: '+str(addr[0])+':'+str(addr[1]))
self.threads.append(Thread(target=self.handle_client, args=(client, addr)))
for thread in self.threads:
thread.start()
def handle_client(self, client_socket, address):
client_socket.send('Welcome to server'.encode())
size = 1024
while True:
message = client_socket.recv(size)
if message.decode() == 'q^':
print('Received request for exit from: '+str(address[0])+':'+str(address[1]))
break
else:
print('Received: '+message.decode()+' from: '+str(address[0])+':'+str(address[1]))
client_socket.send('Received request for exit. Deleted from server threads'.encode())
client_socket.close()
if __name__=="__main__":
main = Server()
Client.py
import socket
import sys, time
def main():
target_host = '127.0.0.1'
target_port = 9999
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print('Could not create a socket')
time.sleep(1)
sys.exit()
try:
client.connect((target_host, target_port))
except socket.error:
print('Could not connect to server')
time.sleep(1)
sys.exit()
while True:
data = input()
client.send(data.encode())
message = client.recv(4096)
print('[+] Received: '+ message.decode())
main()
You have to send exit message 'q^' to client too to close client.
Warning:
Using Unicode as encoding for string is not recommended in socket. A partial Unicode character may be received in server/client resulting in UnicodeDecodeError being raised.
Code for server using threads is:
server.py:
import socket
from threading import Thread
class Server:
def __init__(self, host, port):
self.host = host
self.port = port
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((self.host, self.port))
self.server.listen(5)
def listen_for_clients(self):
print('Listening...')
while True:
client, addr = self.server.accept()
print(
'Accepted Connection from: ' + str(addr[0]) + ':' + str(addr[1])
)
Thread(target=self.handle_client, args=(client, addr)).start()
def handle_client(self, client_socket, address):
size = 1024
while True:
try:
data = client_socket.recv(size)
if 'q^' in data.decode():
print('Received request for exit from: ' + str(
address[0]) + ':' + str(address[1]))
break
else:
# send getting after receiving from client
client_socket.sendall('Welcome to server'.encode())
print('Received: ' + data.decode() + ' from: ' + str(
address[0]) + ':' + str(address[1]))
except socket.error:
client_socket.close()
return False
client_socket.sendall(
'Received request for exit. Deleted from server threads'.encode()
)
# send quit message to client too
client_socket.sendall(
'q^'.encode()
)
client_socket.close()
if __name__ == "__main__":
host = '127.0.0.1'
port = 9999
main = Server(host, port)
# start listening for clients
main.listen_for_clients()
client.py:
import socket
import sys, time
def main():
target_host = '127.0.0.1'
target_port = 9999
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print('Could not create a socket')
time.sleep(1)
sys.exit()
try:
client.connect((target_host, target_port))
except socket.error:
print('Could not connect to server')
time.sleep(1)
sys.exit()
online = True
while online:
data = input()
client.sendall(data.encode())
while True:
message = client.recv(4096)
if 'q^' in message.decode():
client.close()
online = False
break
print('[+] Received: ' + message.decode())
break # stop receiving
# start client
main()
I'm completely newbie to python and computer networking. While working on Uni project I have faced a problem. What am I doing wrong? Any help will me much appreciated.
Here is server side:
import socket
def Main():
host = "127.0.0.1"
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
print ("Server Started.")
while True:
data, addr = s.recvfrom(1024)
print ("message from: ") + str(addr)
print ("from connected user: ") + str(data.decode('utf-8'))
data = str(data).upper()
print ("sending: ") + str(data)
s.sendto(data, addr)
s.close()
if __name__ == '__main__':
Main()
Here is my client side:
import socket
def Main():
host = "127.0.0.1"
port = 5000
server = ('127.0.0.1', 5000)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
message = input('->')
while message != 'q':
s.sendto(message.encode('utf-8'), server)
data, addr = s.recvfrom(1024)
print ('Received from server: ') + str(data)
message = input('->')
s.close()
if __name__ == '__main__' :
Main()
There were a couple of issues; mostly with the printing.
You had a few instances of print('some text') + str(data); this won't work, because while print() outputs to the screen (STDOUT) it returns None, so what you were actually doing was trying to concatenate None + str(data)
What you need is print('some text' + str(data)).
Additionally, there was as issue on the server-side where you echo the data received from the client back to the client- it needed to be re-encoded as a bytearray (it comes in as a bytearray, gets converted to a utf-8 string for display, it needs to go back to bytearray before replying).
In summary, server:
import socket
def Main():
host = "127.0.0.1"
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
print("Server Started.")
while True:
try:
data, addr = s.recvfrom(1024)
print("message from: " + str(addr)) # moved string concatenation inside print method
print("from connected user: " + str(data.decode('utf-8'))) # moved string concatenation inside print method
data = str(data).upper()
print("sending: " + str(data)) # moved string concatenation inside print method
s.sendto(data.encode('utf-8'), addr) # needed to re-encode data into bytearray before sending
except KeyboardInterrupt: # added for clean CTRL + C exiting
print('Quitting')
break
s.close()
if __name__ == '__main__':
Main()
And the client:
import socket
def Main():
host = "127.0.0.1"
port = 5001
server = ('127.0.0.1', 5000)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
message = input('->')
while message != 'q':
try:
s.sendto(message.encode('utf-8'), server)
data, addr = s.recvfrom(1024)
print('Received from server: ' + str(data)) # moved string concatenation inside print method
message = input('->')
except KeyboardInterrupt: # added for clean CTRL + C exiting
print('Quitting')
break
s.close()
if __name__ == '__main__':
Main()
I have a python script that receives tcp data from client and I want to send a response to a specific client (I handle more than 500). This command comes from a mysql database and I handle the clientsocket by a dictionary, but the script is down when it receives a lot of connections.
How can I store the clientsocket in mysql database, or which is the best way to handle the clientsocket?
My code is:
import thread
from socket import *
def sendCommand():
try:
for clientsocket,id_client in conn_dict.iteritems():
if id_cliente == "TEST_from_mysql_db":
clientsocket.send("ACK SEND")
break
except:
print "NO"
def handler(clientsocket, clientaddr):
print "Accepted connection from: ", clientaddr
while 1:
data = clientsocket.recv(buf)
if not data:
break
else:
conn_dict[clientsocket] = id_client
sendCommand()
clientsocket.close()
if __name__ == "__main__":
conn_dict = dict()
host = str("XXX.XXX.XXX.XXX")
port = XXX
buf = 1024
addr = (host, port)
serversocket = socket(AF_INET, SOCK_STREAM)
serversocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serversocket.bind(addr)
serversocket.listen(2)
while 1:
print "Server is listening for connections\n"
clientsocket, clientaddr = serversocket.accept()
thread.start_new_thread(handler, (clientsocket, clientaddr))
serversocket.close()
I am doing an simple Python socket server and client that need to be able to receive few inputs and not losing connection. I can input one command but after receiving the reply the connection is lost. How can i keep it alive?
Client code
import socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except sockets.error , msg:
print 'Failed to create socket, Error code:' + str(msg[0]) + ' , Error message :' + msg[1]
sys.exit()
print 'Socket Created'
host = '127.0.0.1'
port = 8888
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
print 'Hostname could not be resolved. Exiting'
sys.exit()
print 'Ip address of ' + host + ' is ' + remote_ip
s.connect((remote_ip , port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
message = raw_input('Sladu inn skipun :')
try :
s.sendall(message)
except socket.error:
print 'Send failed'
sys.exit()
print 'Message send successfully'
reply = s.recv(4096)
print reply
s.close()
Server code
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import sys
from thread import *
import glob
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(10)
print 'Socket now listening'
def clientthread(conn):
while True:
data = conn.recv(1024)
if data == "show dir":
reply = glob.glob('*.*')
else:
reply ="Þessi skipun hefur ekki verið forrituð"
if not data:
break
conn.send(str(reply))
while 1:
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
start_new_thread(clientthread ,(conn,))
s.close()
Your server code looks okay. But your client is only sending one message and then exiting. Which closes the connection.
Try something like this in your client code:
while True:
message = raw_input('Sladu inn skipun :')
try :
s.sendall(message)
print s.recv(1024)
except socket.error:
print 'Send failed'
sys.exit()