Python3 server not responding to client request - python

I am setting up a basic python application that will listen for UDP packets at a specific port.
I am using an example code found online to begin to familiarize myself with UDP and socket connection.
When I invoke client.py and then server.py - the server does not respond and the terminal remains idle - any solutions for this problem? Below is the basic code I am working with
Client.py
import socket
UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 6789
Message = b"Hello, Server"
clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
clientSock.sendto(Message, (UDP_IP_ADDRESS, UDP_PORT_NO))
Server.py
import socket
UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 6789
serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serverSock.bind((UDP_IP_ADDRESS, UDP_PORT_NO))
while True:
#data, addr = serverSock.recvfrom(1024)
data, addr = serverSock.recvfrom(1024)
print ("Message: ", data)

When I invoke client.py and then server.py
Well that's your problem--by invoking the client which sends, then later invoking the server which receives, you are preventing the two from communicating. The server needs to be running at the moment the client sends.

Related

Socket doesn't work when using public ip on same machine

I made a program using Python that should connect to the server using a socket. I run the script on the same machine and when I tried with private ip it worked but public doesn't.
Client:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("46.126.xx.xxx",9454)) #I put the public ip of the server (same machine)
msg = s.recv(1024)
print(msg.decode("utf-8"))
Server
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("0.0.0.0",9454))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f"Connection from {address} has been established!")
clientsocket.send(bytes("Welocme to the server", "utf-8"))
It does not give me any errors. I made lots of reasearch but couldn't figure out what the problem is.
Well I just put the public ip of the server in the client socket.connect() and expected it to connect but it didn't. I am running this on the same machine.

Connect python local server with godot

I'm trying to send data to a python server:
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('127.0.0.1',6000))
s.listen(5)
while True:
clientsocket,address = s.accept()
print(f"Got connection from {address} !")
from godot:
var socket = PacketPeerUDP.new()
socket.set_dest_address("127.0.0.1",6000)
socket.put_packet("quit".to_ascii())
based on this link
but it doesn't seem to be working, How do I send the data?
i'm not that familiar with python servers, but it looks like you have a python server that listens for TCP connections but in godot you connect via UDP Client.
As seen in this Answer SOCK_STREAM is for TCP Server and SOCK_DGRAM for UDP.
I am not sure which of those you want to use. An example server for UDP would be:
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(('127.0.0.1',6000))
bufferSize = 1024
#s.listen(5)
print("running")
while True:
bytesAddressPair = s.recvfrom(bufferSize)
message = bytesAddressPair[0]
clientMsg = "Message from Client:{}".format(message)
print(clientMsg)
I copied most of it from here : Sample UDP Server
If you wanted to have a TCP Server you should alter the Godot part to use a TCP Client. See the official docs here
figured it out thanks to #René Kling 's answer
just incase someone wants the complete version
python server:
import socket
HOST = "127.0.0.1"
PORT = 6000
s= socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind((HOST, PORT))
while True:
message, addr = s.recvfrom(1024)
print(f"Connected by {addr}")
Godot:
extends Node2D
tool
export(bool) var btn =false setget set_btn
var socket = PacketPeerUDP.new()
func set_btn(new_val):
socket.set_dest_address("127.0.0.1", 6000)
socket.put_packet("Time to stop".to_ascii())

PC can be UDP client but not UDP Server. Why?

I am trying to set up a Raspberry pi to transmit data to my PC via UDP. To do this, both devices are connected to my mobile hotspot.
PC IP: 192.168.78.1
RasPi IP: 192.168.78.57
There are two scripts:
UDP Server
import socket
UDP_IP = '192.168.78.1' #Used when PC is server
#UDP_IP = '192.168.78.57' #Used when RasPi is server
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind((UDP_IP,UDP_PORT))
data,addr = sock.recvfrom(4096)
print(str(data))
message = "Hello, I am the UDP Server"
sock.sendto(message.encode("utf-8"), addr)
sock.close()
UDP Client
import socket
UDP_IP = '192.168.78.1' #Used when PC is server
#UDP_IP = '192.168.78.57' #Used when RasPi is server
UDP_PORT = 5005
client_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
message = 'Hi, this is a client'
client_socket.sendto(message.encode("utf-8"),(UDP_IP,UDP_PORT))
data,addr = client_socket.recvfrom(4096)
print('Server Says')
print(str(data))
client_socket.close()
The client sends a message to the server and receives a message in response.
When I run the server code on the RasPi and the client code on the PC, everything works fine.
However, when I run the server code on the PC and the client code on the Raspi, it does not work.
The server gets stuck on the line data,addr = sock.recvfrom(4096) presumably waiting for a message, while the client gets stuck on the line client_socket.sendto(message.encode("utf-8"),(UDP_IP,UDP_PORT)) presumably trying to send the message.
Can anyone help me explain why the connection works with the RasPi as the server but not with the PC as the server?

Socket server in python refuses to connect

I am trying to create a simple web server with python using the following code.
However, When I run this code, I face this error:
ConnectionRefusedError: [WinError 10061] No connection could be made
because the target machine actively refused it
It worths mentioning that I have already tried some solutions suggesting manipulation of proxy settings in internet options. I have run the code both in the unticked and the confirmed situation of the proxy server and yet cannot resolve the issue.
Could you please guide me through this ?
import sys
import socketserver
import socket
hostname = socket.gethostname()
print("This is the host name: " + hostname)
port_number = 60000
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.connect((hostname,port_number))
Standard EXAMPLE of socket connection
SERVER & CLIENT
run this in your IDLE
import time
import socket
import threading
HOST = 'localhost' # Standard loopback interface address (localhost)
PORT = 60000 # Port to listen on (non-privileged ports are > 1023)
def server(HOST,PORT):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while True:
conn, addr = s.accept()
data = conn.recv(1024)
if data:
print(data)
data = None
time.sleep(1)
print('Listening...')
def client(HOST,PORT,message):
print("This is the server's hostname: " + HOST)
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.connect((HOST,PORT))
soc.send(message)
soc.close()
th=threading.Thread(target = server,args = (HOST,PORT))
th.daemon = True
th.start()
After running this, in your IDLE execute this command and see response
>>> client(HOST,PORT,'Hello server, client sending greetings')
This is the server's hostname: localhost
Hello server, client sending greetings
>>>
If you try to do server with port 60000 but send message on different port, you will receive the same error as in your OP. That shows, that on that port is no server listening to connections

Python UDP Socket File Transfer

How do I get a response from the server?
Client side:
#CLIENT
import socket
import time
host = "localhost"
port = 5454
data_c = input()
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
c.sendto(bytes(data_c, 'utf-8'),(host,port))
print( data_c )
print( c.recv(1024).decode('utf-8'))
SERVER side:
#SERVER
import socket
import time
host = "localhost"
port = 5454
data_s = "ACKNOWLEDGMENT"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
print(s.recv(1024).decode('utf-8'))
I can send a message from the server that the client will receive, but can not seem to get communication (like an ACK.) to make it back to the server.
(yes UDP is not a good way to be doing this i'm pretty sure, but that was a specific for the project)
for question 1: to send the ACK, you could replicate what you have in the reverse direction.
Since UDP is connection-less you don't know beforehand you receive a packet where the packet will come from, so you have to use recvfrom to get both the packet and the peer (address/port) the packet came from. Then you have to use that address to send data back.
What you're doing now in your client (but what really looks like the server) in the loop is send the same data over and over to itself. Instead in the loop you should receive packets using the previously mentions recvfrom then send replies to the peer you received the packet from.
So something like the following pseudo code
while True:
peer = recvfrom(...)
sendto(..., peer)
After many attempts to get a simple acknowledgment reply from my server this did it.
Beyond literally starting completely over each round, the time.sleep(.1) function was the only missing key. It allowed the server and client both time to close the current socket connection so that there was not an error of trying to bind multiple bodies to a single location or something.
OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
Working result:
#SERVER
import socket
import time
host = "localhost"
port = 5454
data_s = "ACKNOWLEDGMENT"
while 1:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
received = print("Client: " + s.recv(1024).decode('utf-8')) #waiting to receive
s.close
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
time.sleep(.1)
s.sendto(bytes(data_s, 'utf-8'),(host,port)) #sending acknowledgment
print("Server: " + data_s)
s.close # close out so that nothing sketchy happens
time.sleep(.1) # the delay keeps the binding from happening to quickly
Server Command Window:
>>>
Client: hello
Server: ACKNOWLEDGMENT
Client:
#CLIENT
import socket
import time
host = "localhost"
port = 5454
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while 1:
data_c = input("Client: ")
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
c.sendto(bytes(data_c, 'utf-8'),(host,port)) #send message
c.close
# time.sleep()
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
c.bind((host, port))
print("Server: " + c.recv(1024).decode('utf-8')) # waiting for acknowledgment
c.close
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
time.sleep(.1)
Client Command Window:
>>>
Client: hello
Client: hello
Server: ACKNOWLEDGMENT
I did finally remove the redundant input("Client: ") there at the top.
A special thanks #JoachimPileborg for helping, but I have to give it to the little guy just because it was the path I ended up taking.

Categories

Resources