python socket send not working - python

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

Related

How to let the server socket react to a second client request?

I have a simple echo server that echos back whatever it receives. This works well for a single client request.
# echo-server.py
import socket
HOST = "127.0.0.1"
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
while True:
try:
data = conn.recv(1024)
except KeyboardInterrupt:
print ("KeyboardInterrupt exception captured")
exit(0)
conn.sendall(data)
# echo-client.py
import socket
HOST = "127.0.0.1" # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello, world")
data = s.recv(1024)
print(f"Received {data!r}")
However, if I finish one client request, and do a second client request, the server no more echoes back. How can I solve this issue?
(base) root#40029e6c3f36:/mnt/pwd# python echo-client.py
Received b'Hello, world'
(base) root#40029e6c3f36:/mnt/pwd# python echo-client.py
On the server side, you need to accept connections in an infinite loop. This should work.
server.py
HOST = "127.0.0.1"
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
print(f"Connected by {addr}")
try:
data = conn.recv(1024)
except KeyboardInterrupt:
print ("KeyboardInterrupt exception captured")
exit(0)
conn.sendall(data)

Connecting client and server in python the code below dont give output make browser busy

This code is not giving output it just makes the browser busy. Any idea why?
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect(('127.0.0.1', port))
print (s.recv(1024))
s.close
import socket
s=socket.socket()
host = socket.gethostname()
port = 12345
s.bind(('127.0.0.1', port))
s.listen(5)
while True:
c,addr = s.accept()
print ('Got connection from', addr)
c.send('Thank you for connecting')
c.close()
client program:
import socket
f=open("hello.txt","r").read()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 12345
s.connect(('127.0.0.1', port))
s.sendall(str.encode(f))
print (s.recv(1024).decode('ascii'))
s.close()
server program:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket successfully created")
port = 12345
s.bind(('', port))
print ("socket binded to %s" %(port))
f=open("hi.txt","r").read()
s.listen(5)
print ("socket is listening")
while True:
c, addr = s.accept()
print ('Got connection from', addr)
print (c.recv(1024).decode('ascii'))
c.sendall(str.encode(f))
c.close()
server output:
Socket successfully created
socket binded to 12345
socket is listening
Got connection from ('127.0.0.1', 51630)
helloooooo
client output:
hiiiii
Open the two programs in seperate shells.
Run server program first then client program.
Dont close the server program before running client program.
Create two files one for server and one for client.
Read the data from those files and send it.
While receiving the data decode it and print it.
You can send entire data from files or just a single line it depends on you.
To know more about reading,writing and creating files you can refer https://docs.python.org/release/3.6.5/tutorial/inputoutput.html#reading-and-writing-files
Let me know if it worked :)

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

Why is this server program not able to send anything to the client?

I am basically trying to make a chatting app but here I am unable to send anything from the server to the client. How do I correct this?
server program:
from socket import *
host=gethostname()
port=7777
s=socket()
s.bind((host, port))
s.listen(5)
print "Server is Ready!"
while True:
c, addr= s.accept()
print c
print addr
while True:
print c.recv(1024)
s.sendto("Received",addr)
s.close()
client program:
from socket import *
host=gethostname()
port=7777
s=socket()
s.connect((host, port))
while True:
s.send(( raw_input()))
prin s.recv(1024)
s.close()
It is giving me error at s.sendto in server program saying:
File "rserver.py", line 14, in <module>
s.sendto("Received",addr)
socket.error: [Errno 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
You cannot use the connection socket to send or receive objects so the problem is there only....
Use -
c.sendto("Received", addr)
instead of
s.sendto("received", addr)
Second problem is you are not receiving the messages from the socket... Here is the working code
server.py -
from socket import *
host=gethostname()
port=7777
s=socket()
s.bind((host, port))
s.listen(5)
print "Server is Ready!"
while True:
c, addr= s.accept()
print c
print addr
while True:
print c.recv(1024)
#using the client socket and make sure its inside the loop
c.sendto("Received", addr)
s.close()
client.py
from socket import *
host=gethostname()
port=7777
s=socket()
s.connect((host, port))
while True:
s.send(( raw_input()))
#receive the data
data = s.recv(1024)
if data:
print data
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.

Categories