How to produce correct endless socket connection? - python

I need to produce endless socket connections, which can be broke only with 1KeyboardInterupt1 or special word.
When I start both programs in different IDEs, the sender asks to input the message. But only the first message sends to the server and all the others don't.
I need to produce an endless cycle, where all inputs are sent to the server on print.
The server part:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 8888))
s.listen(5)
while True:
try:
client, addr = s.accept()
except KeyboardInterrupt:
s.close()
break
else:
res = client.recv(1024)
print(addr, 'says:', res.decode('utf-8'))
And the client:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8888))
while True:
com = input('Enter the message: ')
s.send(com.encode())
print('sended')
if com == 'exit':
s.close()
break
I tried to do this on the client:
import socket
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8888))
com = input('Enter the message: ')
s.send(com.encode())
print('sended')
s.close()
if com == 'exit':
break
But this way needs to create a socket, make connection and close socket every iteration.
Is there the way how to do what I described above with only one socket initialization?

The s.close() must be out of the while loop.

Related

Python socket programming , how to communicate with another computer in the same network

#SOLVED#
It is solved when i disable Microsoft FireWall...
I want to make a basic multiplayer game using pygame and socket.
I created two scripts server.py and client.py .
I can send data from one pythonwindow to anotherwindow in the same computer but I want to send data to another window in another computer that connects the same internet connection.
How could it be possible ? Thank you
server.py
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ipv4 = socket.gethostbyname(socket.gethostname())
port = 1233
server_socket.bind((ipv4, port))
#Listens for new connections.
server_socket.listen(5)
#5 is backlog parameter that means while server is busy keep 5 connections.
# If sixth connection comes it will immediately be refused.
connection = True
while connection:
print("Server is waiting for connection.")
client_socket,addr = server_socket.accept()
print("client connected from {}".format(addr))
while True:
data = client_socket.recv(1024)
#Max 1024 bytes can be received and the max amount of bytes is given as parameter.
if not data or data.decode("utf-8") == "END":
connection = False
break
print("received from client : {a}".format(a = data.decode("utf-8")))
try:
client_socket.send(bytes("Hey client","utf-8"))
except:
print("Exited by the user")
client_socket.close()
server_socket.close()
client.py
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ipv4 = socket.gethostbyname(socket.gethostname())
port = 1233
print(ipv4)
#Connection of client to the server.
client_socket.connect((ipv4, port))
message = "Hey naber moruk nasilsin? Ben gayet iyiyim."
try :
while True:
client_socket.send(message.encode("utf-8"))
data = client_socket.recv(1024)
print(str(data))
more = input("Want to send more data to the server ? ('yes' or 'no')")
if more.lower() == "y":
message = input("Enter Payload")
else:
break
except KeyboardInterrupt:
print("Exited by the user")
client_socket.close()

Python TCP server receives only one message out of multiple messages

I have simple code that asks multiple inputs from user and sends it to the server but the server only recieves the first message. How can I make the server get rest of the messages?
Client:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',8000))
for i in range(1,3):
message = input("Enter your message:")
s.send(message.encode())
s.close()
Server:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 8000))
s.listen(1)
print('ready')
while True:
c,addr = s.accept()
sentence = c.recv(1024)
print(sentence.decode())
c.close()
I think the problem is in the server.py line 7. It awaits to accept connection therefore does not wait to receive data.
For server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 8000))
s.listen(1)
print('ready')
c,addr = s.accept()
while True:
sentence = c.recv(1024)
if sentence:
print(sentence.decode())
c.close()
For the client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',8000))
for i in range(1,3):
message = input("Enter your message:")
s.send(message.encode())
s.close()

How to write a python echo server that doesn't disconnect after first echo?

I want to set up a simple echo server that just echoes back whatever the client sends to it. However, currently the server disconnects (the server socket closes) after it echoes back the first client message. I want to be able to "chat" continuously with the server, where the server just echoes back several consecutive messages I send without disconnecting; e.g.:
"Hi there!"
"Echoing: Hi there!"
"How are you?"
"Echoing: How are you?"
"Cheers!"
"Echoing: Cheers!"
etc.
Currently I have the following code:
server.py:
import socket
HOST = '127.0.0.1'
PORT = 5000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
client.py:
import socket
HOST = '127.0.0.1'
PORT = 5000
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('Echoing: ', repr(data))
The server, however, disconnects after it echoes back the first client message (probably because of the if not data: break statement).
P.S. I'd appreciate any additional explanations which might be necessary - this example has educational purposes, so I'm not (only) after getting the code running.
Thanks!
server.py:
import socket
HOST = '127.0.0.1'
PORT = 5000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
while True:
data = conn.recv(1024)
if data.decode() == "bye":
break
conn.sendall(data)
conn, addr = s.accept()
I will show you the code I created then talk you through it:
Server:
import socket
HOST = '127.0.0.1'
PORT = 5000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
while True:
data = conn.recv(1024)
conn.sendall(data)
For the server I removed:
if not data:
break
It simply wasn't working for me. If you know your message is going to be less than the 1024 bytes( which here it is) it's unnecessary. But if you want a longer message change that value to a bigger number to accommodate. So yes you were right in suspecting it was that line.
Client:
import socket
HOST = '127.0.0.1'
PORT = 5000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
print("Connected")
while True:
print("Sending data")
s.sendall(b'Hello, world')
print("Recieving data")
data = s.recv(1024)
print('Echoing: ', repr(data))
For the client side I just added the send and receive process into a loop.
Things to note:
This only works for me when run through the terminal, I don't know if you know how to do that so sorry if you do, here's a link explaining:
https://www.wikihow.com/Use-Windows-Command-Prompt-to-Run-a-Python-File
I assumed you use Windows.
You will need to follow the process for both your client.py programme and server.py programme. Make sure you run the server.py programme first.
This will cause an infinite loop of sending and receiving. Press Ctrl+C to terminate.
I hope this solves your problem and you can edit the code accordingly. Any further problems please do comment and I'll try to get back to you.
Maybe use sleep instead of break
if not data:
time.sleep(1)
continue
You have to import time module for this.

How can python socket client receive without being blocked

A simple demo of socket programming in python:
server.py
import socket
host = '127.0.0.1'
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
while True:
data = conn.recv(1024)
print 'Received:', data
if not data:
break
conn.sendall(data)
print 'Sent:', data
conn.close()
client.py
import socket
host = '127.0.0.1'
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall('Hel')
s.sendall('lo world!')
print 'Received:', s.recv(1024)
s.close()
Now code work well. However, the client may not know if server will always send back every time. I tried symmetric code of while-loop in server.py
client_2.py
import socket
host = '127.0.0.1'
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall('Hel')
s.sendall('lo world!')
while True:
data = s.recv(1024)
if not data:
break
print 'Received:', data
s.close()
This code will block at
data = s.recv(1024)
But in server.py, if no data received, it will be blank string, and break from while-loop
Why it does not work for client? How can I do for same functionality without using timeout?
You can set a socket to non-blocking operation via socket.setblocking(false), which is equivalent to socket.settimeout(0). Solving this "without using timeout" is impossible.

My Python socket server can only receive one message from the client

Hi i got a problem with my socket server or the client the problem is i can only send one message from the client to the server then the server stops receiving for some reason i want it to receive more then one.
Server.py
import socket
host = ''
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print ("Connection from", addr)
while True:
databytes = conn.recv(1024)
if not databytes:
break
data = databytes.decode('utf-8')
print("Recieved: "+(data))
if data == "dodo":
print("hejhej")
if data == "did":
response = ("Command recived")
conn.sendall(response.encode('utf-8'))
conn.close()
client.py
import socket
host = '127.0.0.1'
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print("Connected to "+(host)+" on port "+str(port))
initialMessage = input("Send: ")
s.sendall(initialMessage.encode('utf-8'))
while True:
response = input("Send: ")
if response == "exit":
s.sendall(response.encode('utf-8'))
s.close()
There is nothing wrong with your code, but the LOGIC of it is wrong,
in the Client.py file and particularly in this loop:
while True:
response = input("Send: ")
if response == "exit":
s.sendall(response.encode('utf-8'))
This will not send to your Server side anything but string exit because of this:
if response == "exit":
So you are asking your Client.py script to only send anything the user inputs matching the string exit otherwise it will not send.
It will send anything at the beginning before this while loop since you wrote:
initialMessage = input("Send: ")
s.sendall(initialMessage.encode('utf-8'))
But after you are inside that while loop then you locked the s.sendall to only send exit string
You have to clean up your code logic.

Categories

Resources