Connect python local server with godot - python

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

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.

How to send messages to a remote computer using python socket module?

I'm trying to send a message from a computer to a another computer that is not connected to the other computer local network.
I did port forwarding (port 8080, TCP) and I didn't manage to get the remote computer to connect and to send the message.
when i try to connect it's just getting stuck on the connect method (client).
I also need to mention that I'm open to change anything in the router settings.
the client code (remote computer):
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("%My public IP address%", 8080))
msg = s.recv(1024)
msg = msg.decode("utf-8")
print(msg)
the server code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("192.168.0.2", 8080))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f"Connection from {address} has been established.")
clientsocket.send(bytes("Hey there!!", "utf-8"))
clientsocket.close()
From my understanding, your aim is to connect to a server from a remote computer and send a message from the server to the client. As such, all it requires is the client to connect to the external-facing IP address of your server. Once that is done, router simply forwards the traffic according to the port forwarding rules.
Server:
import socket
def Main():
host = '10.0.0.140'
port = 42424
s = socket.socket()
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
while True:
data = c.recv(1024)
if not data:
break
data = str(data).upper()
c.send(data)
c.close()
if __name__ == '__main__':
Main()
Client:
import socket
def Main():
host = '10.0.0.140' #The host on your client needs to be the external-facing IP address of your router. Obtain it from here https://www.whatismyip.com/
port = 42424
s = socket.socket()
s.connect((host,port))
message = raw_input("->")
while message != 'q':
s.send(message)
data = s.recv(1024)
message = raw_input("->")
s.close()
if __name__ == '__main__':
Main()
Also do note that, When connecting to a server behind a NAT firewall/router, in addition to port forwarding, the client should be directed to the IP address of the router. As far as the client is concerned, the IP address of the router is the server. The router simply forwards the traffic according to the port forwarding rules.

Trying to make a server with sockets in python

I'm trying to make a chat app in Python and I'm having some trouble.
I made a server on which I can connect successfully by using the local IP address. However, when I try to connect to it on an another device with my public IP address, there seems to be a timeout, no errors occur and it's continuously trying to connect.
Edit: I've already set up port-forwarding for my IPv4 address. And the client is using the public IP.
server.py:
import socket
s = socket.socket()
host = socket.gethostbyname(socket.gethostname())
port = 2000
s.bind((host, port))
print("Server started, waiting for incoming connections")
s.listen(5)
connection, address = s.accept()
print("New connection from", address)
while True:
data = connection.recv(1024).decode()
print("received:", data)
ret = data + "+++++++"
connection.send(ret.encode())
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = #my public ip address from whatsmyip.com
port = 2000
s.connect((host, port))
print("Connected.")
while True:
message = input("msg: ")
s.send(message.encode())
data = s.recv(1024).decode()
print(data)
Well, first of all, is your server in a network with other devices? If you have a router there, the IP you see in whatsmyip.com is the router's, not your computer's, IP. So you'd be trying to connect to it.
You can check that with the command netstat.

Python3 server not responding to client request

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.

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