TCP threaded python - python

I'm learning some Networking through Python and came up with this idea of TCPServer Multithread so i can have multiple clients connected. The problem is that i can only connect one client.
import socket
import os
import threading
from time import sleep
from threading import Thread
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket Preparado...')
def Main():
host = '127.0.0.1'
port = 5000
s.bind((host, port))
print('Enlaze listo...')
print('Escuchando...')
s.listen(5)
c, addr, = s.accept()
os.system('cls')
print('Conexion desde: '+str(addr))
def handle_client(client_socket):
while True:
data = client_socket.recv(1024).decode('utf-8')
if not data: break
print('Client says: ' + data)
print('Sending: ' + data)
client_socket.send(data.encode('utf-8'))
client_socket.close()
if __name__ == '__main__':
while True:
Main()
client_socket, addr = s.accept()
os.system('cls')
print('Conexion desde: '+str(addr))
Thread.start_new_thread(handle_client ,(client_socket,))
s.close()
Edit: This is my actual code, to test it i open up two Client.py codes and try to connect to it. The first Client.py successfully connects (Although there's bugs in receiving and sending back info)The second one executes but it's not shown in the server output as connected or something, it just compiles and stays like that.

You need to create a new thread each time you get a new connection
import socket
import thread
host = '127.0.0.1'
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket Ready...')
s.bind((host, port))
print('Bind Ready...')
print('Listening...')
s.listen(1)
def handle_client(client_socket):
while True:
data = client_socket.recv(1024)
if not data: break
print('Client says: ' + data)
print('Sending: ' + data)
client_socket.send(data)
client_socket.close()
while True:
client_socket, addr = s.accept()
print('Conexion from: '+str(addr))
thread.start_new_thread(handle_client ,(client_socket,))
s.close()

Ok, here's the code solved, i should have said i was working on Python3 version. Reading the docs i found out, here's the code and below the docs.
import socket
import os
import threading
from time import sleep
from threading import Thread
import _thread
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket Preparado...')
def Main():
host = '127.0.0.1'
port = 5000
s.bind((host, port))
print('Enlaze listo...')
print('Escuchando...')
s.listen(1)
def handle_client(client_socket):
while True:
data = client_socket.recv(1024).decode('utf-8')
if not data: break
print('Client says: ' + data)
print('Sending: ' + data)
client_socket.send(data.encode('utf-8'))
client_socket.close()
if __name__ == '__main__':
Main()
while True:
client_socket, addr = s.accept()
os.system('cls')
print('Conexion desde: '+str(addr))
_thread.start_new_thread(handle_client ,(client_socket,))
s.close()
https://docs.python.org/3/library/threading.html
http://www.tutorialspoint.com/python3/python_multithreading.htm
The problem was at _thread.start_new_thread(handle_client ,(client_socket,)) just import _thread ask some questions here, keep researching and got it.
Thanks all of you.
WhiteGlove

Related

Locking another computer using sockets without interrupting the connection

I am trying to set up a server that can send each client - commands.
One command is 'lock' which locks the screen of the client.
When a client gets the word "lock" it runs this code on the client:
import ctypes
ctypes.windll.user32.LockWorkStation()
This code does lock the screen however- it ends my connection with the client..
How can I make the client stay connected but still locked?
Note: The locking is not forever! it is only once, like putting the client's computer in sleep mode until he wants to unlock the screen.
Hope I was clear enough. Thanks for helping!
Server:
import socket
def main():
sock = socket.socket()
sock.bind(('0.0.0.0', 4582))
print("Waiting for connections...")
sock.listen(1)
conn, addr = sock.accept()
print ("New connection from: ", addr)
while 1:
command = input("Enter command> ")
if command == 'shutdown':
sock.send(b'shutdown')
elif command == 'lock':
sock.send(b'lock')
else:
print ("Unknown command")
data = sock.recv(1024)
print (data)
if __name__ == '__main__':
main()
Client:
import socket
import ctypes
def main():
sock = socket.socket()
sock.connect(('127.0.0.1', 4582))
while 1:
data = sock.recv(1024)
print (data)
if data == 'lock':
sock.send(b'locking')
ctypes.windll.user32.LockWorkStation()
sock.recv(1024)
if __name__ == '__main__':
main()
I adapted the example from the Python docs to your needs.
Example for server.py:
import socket
HOST = '127.0.0.1'
PORT = 4582
with socket.socket() as s:
print('Waiting for connection...')
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = input('Which command? ')
if data in ['lock', 'shutdown']:
conn.send(data.encode())
else:
print('Command unknown')
Example for client.py:
import ctypes
import socket
HOST = '127.0.0.1'
PORT = 4582
with socket.socket() as s:
s.connect((HOST, PORT))
while True:
data = s.recv(1024).decode()
if not data:
print('Server disconnected')
break
print('Received command:', data)
if data == 'shutdown':
print('Shutting down client...')
break
if data == 'lock':
print('Locking...')
ctypes.windll.user32.LockWorkStation()

Trying to create messenger application python

Trying to Create Messenger Application within python (cross internet). So far I have successfully been able to send a message to the receiver end and then ping the message back to the user that sent it. However, it does not send the message to all connected users. I think this is because if python is listening for user input the socket cannot receive any data (I might be wrong...).
Below is the client side code:
import socket
host = '**.***.***.***' # Public Ip Hidden
port = 5005 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
b = input("Please enter your message.")
b = b.encode('utf-8')
s.sendall(b)
while True:
data = s.recv(1024)
print('Message Received:', repr(data))
Now below is the server side code:
import socket
import sys
import os
import thread
import threading
from thread import *
from threading import Thread
HOST = '' # Symbolic name meaning all available interfaces
PORT = 5005 # Arbitrary non-privileged port
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client = ''
clients = set()
clients_lock = threading.Lock()
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#infinite loop so that function do not terminate and thread do not end.
with clients_lock:
clients.add(client)
while True:
#Receiving from client
data = conn.recv(1024)
if not data:
break
else:
print repr(data)
with clients_lock:
for c in clients:
for d in data:
conn.sendall(data)
print(data.decode("utf-8"))
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
start_new_thread(clientthread ,(conn,))
s.close()
Any Suggestions would be much appreciated.

How to avoid the following discrepancy in my chatting app between client and server?

As in my chatting app here, when client sends a message sends a message to server it becomes necessary for server to send a reply before client can send a message again. How to avoid this?
Server program:
from socket import *
import threading
host=gethostname()
port=7776
s=socket()
s.bind((host, port))
s.listen(5)
print "Server is Ready!"
def client():
c, addr= s.accept()
while True:
print c.recv(1024)
c.sendto(raw_input(), addr)
for i in range(1,100):
threading.Thread(target=client).start()
s.close()
Client program:
from socket import *
host=gethostname()
port=7776
s=socket()
s.connect((host, port))
while True:
s.send(( raw_input()))
data= s.recv(1024)
if data:
print data
s.close()
I am pretty sure you were meant to make the central server receive messages from clients, and send them to all other clients, was it not? What you implemented isn't exactly that - instead, the server process just prints all messages that arrive from the clients.
Anyways, based on the way you implemented it, here's a way to do it:
Server:
from socket import *
import threading
def clientHandler():
c, addr = s.accept()
c.settimeout(1.0)
while True:
try:
msg = c.recv(1024)
if msg:
print "Message received from address %s: %s" % (addr, msg)
except timeout:
pass
host = "127.0.0.1"
port = 7776
s = socket()
s.bind((host, port))
s.listen(5)
for i in range(1, 100):
threading.Thread(target=clientHandler).start()
s.close()
print "Server is Ready!"
Client:
from socket import *
host = "127.0.0.1"
port = 7776
s = socket()
s.settimeout(0.2)
s.connect((host, port))
print "Client #%x is Ready!" % id(s)
while True:
msg = raw_input("Input message to server: ")
s.send(msg)
try:
print s.recv(1024)
except timeout:
pass
s.close()

Python socket multiple calls using Eventlet

I need to call a socker server multiple times and print its output.
Here is my below code:-
server.py
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
print "Server started"
while True:
c, addr = s.accept()
print('Got connection from', addr)
#sprint('Received message == ',c.recv(50))
s = c.recv(50)[::-1]
c.send(s)
c.close()
client.py
import socket
from time import sleep
import eventlet
def socket_client():
s = socket.socket()
host = socket.gethostname()
port = 1234
s.connect((host, port))
print "Sending data"
s.sendall("Hello!! How are you")
print(s.recv(1024))
#socket_client()
pile = eventlet.GreenPile()
for x in range(10):
print 'new process started'
pile.spawn(socket_client())
print 'new process started over'
print 'over'
I use a python eventlet to call the socket_client() 10 times but its not returning the correct result..
You're overriding variable with socket by string received from socket:
s = socket.socket()
...
s = c.recv(50)[::-1]
Pick different variable name for the second case.

python socket send not working

Im writing a simple socket program to receive some data and reverse the contents.
When I pass the reversed contents its not being sent..
Server
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print('Got connection from', addr)
print('Received message == ',c.recv(50))
s = c.recv(50)[::-1]
c.send(s)
c.close()
client
import socket
from time import sleep
s = socket.socket()
host = socket.gethostname()
port = 1234
s.connect((host, port))
print "Sending data"
s.sendall("Hello!! How are you")
print(s.recv(1024))
The problem is two lines in your server
Your server calls recv() inside a print statement. This empties the buffer. Then you call recv() again, but it is already emptied by the previous statement and so it then blocks.
You need to call recv() and store that in s. Then use s everywhere else.
Try this for your server:
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print('Got connection from', addr)
s = c.recv(50)
print('Received message == ',s)
c.send(s)
c.close()

Categories