Python socket multiple calls using Eventlet - python

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.

Related

TCP threaded 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

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

Errno 98: Address already in use - Python Socket

This question has been asked before but none of the answers was helpful in my case. The problem seems very simple. I am running a TCP server on an raspberry pi and try to connect to it from another machine. I have a custom class receiver that pipes sensor data to this script.
When I close the program running on the other machine (the socket is 'shutdown(2)'d and then 'close()'d), I cannot reconnect to that same port anymore. I tried to alternate between two sockets (1180 and 1181) but this did not work. When I connect over a port once, it is gone forever until I restart the TCP server. I tried restarting the script (with executl()) but that did not resolve my problem. I am telling the socket that it should re-use addresses but to no avail.
What I could do is use more ports but that would require opening more ports on the RPi which I would like to avoid (there must be another way to solve this).
import socket
from receiver import receiver
import pickle
import time
import os
import sys
TCP_IP = ''
TCP_PORT = 1180
BUFFER_SIZE = 1024
print 'Script started'
while(1):
try:
print 'While begin'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print 'Socket created'
s.settimeout(5)
print 'Trying to bind'
s.bind((TCP_IP, TCP_PORT))
print 'bound to', (TCP_IP, TCP_PORT)
s.listen(1)
print 'listening for connection'
conn, addr = s.accept()
print 'accepted incoming connection'
s.settimeout(5)
r = receiver()
print 'Connection address:', addr
for cur in r:
#print "sending data:", cur
print len(cur.tostring())
conn.send(cur.tostring()) # echo
except Exception as e:
r.running = False
print e
if TCP_PORT == 1181:
TCP_PORT = 1180
else:
TCP_PORT = 1181
time.sleep(1)
print 'sleeping 1sec'
Your server socket is still in use, so you cannot open more than one server socket for each port. But why should one. Just reuse the same socket for all connections (that's what server sockets made for):
import socket
from receiver import receiver
import logging
TCP_IP = ''
TCP_PORT = 1180
BUFFER_SIZE = 1024
print 'Script started'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print 'Trying to bind'
server.bind((TCP_IP, TCP_PORT))
print 'bound to', (TCP_IP, TCP_PORT)
server.listen(1)
print 'listening for connection'
while True:
try:
conn, addr = server.accept()
print 'accepted incoming connection'
print 'Connection address:', addr
for cur in receiver():
data = cur.tostring()
#print "sending data:", cur
print len(data)
conn.sendall(data) # echo
except Exception:
logging.exception("processing request")

Simple Python chat app with sockets

I'm trying to make a simple client/server chat app in Python with sockets, and eventually turn it into a networked game of Rock, Paper, Scissors.
I found a guide online to create the client/server but I'm having trouble modifying the loops so that each script listens for the other, receives a message, then shows a raw_input that becomes the message sent to the other script, then so on. Here's the code:
client.py
#!/usr/bin/python
import socket
s = socket.socket()
host = socket.gethostname()
port = 12221
s.connect((host, port))
while True:
z = raw_input("Enter something for the server: ")
s.send(z)
print s.recv(1024)
server.py
#!/usr/bin/python
import socket
s = socket.socket()
host = socket.gethostname()
port = 12221
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print 'Got connection from', addr
print c.recv(1024)
q = raw_input("Enter something to this client: ")
c.send(q)
Any help? Thank you.
Like #DavidCullen said in the comments, you are halting on the second time through the while loop for the server to accept a new connection.
You can get around that by doing an if-connected check. I also added some print statements so you could clearly debug what is happening.
server.py
#!/usr/bin/python
import socket
s = socket.socket()
host = socket.gethostname()
port = 12221
s.bind((host, port))
s.listen(5)
c = None
while True:
if c is None:
# Halts
print '[Waiting for connection...]'
c, addr = s.accept()
print 'Got connection from', addr
else:
# Halts
print '[Waiting for response...]'
print c.recv(1024)
q = raw_input("Enter something to this client: ")
c.send(q)
client.py
#!/usr/bin/python
import socket
s = socket.socket()
host = socket.gethostname()
port = 12221
s.connect((host, port))
print 'Connected to', host
while True:
z = raw_input("Enter something for the server: ")
s.send(z)
# Halts
print '[Waiting for response...]'
print s.recv(1024)

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