[UDP] How to send UDP messages on Unity and receive UDP messages on Python? Is there an example? The example of the document does not work #25
-
How to send UDP messages on Unity and receive UDP messages on Python? Is there an example? The example of the document does not work |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments 21 replies
-
You can use Netly on dotnet side. but on python side you must find example about here. but don't angry im creating tests on give you example:
|
Beta Was this translation helpful? Give feedback.
-
亲,您的来信可能不能及时看到,看到后必定第一时间回复!
|
Beta Was this translation helpful? Give feedback.
-
Client
|
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
Well i think you wish use Unity as UdpServer and Pyhton as UdpClient. using now: // unity server
using System;
using Netly;
using Netly.Core;
using UnityEngine;
class NetlyUdp : MonoBehaviour
{
private readonly UdpServer server = new UdpServer(useConnection: false);
public string message = "";
public String ip = "127.0.0.1";
public int port = 12000;
private void Start()
{
server.OnOpen(() => Debug.Log("UDP Server, started."));
server.OnClose(() => Debug.Log("UDP Server, disconnected."));
server.OnError((exception) => Debug.Log($"UDP Server, error: {exception}."));
server.OnData((UdpClient newUdpClient, byte[] bytes) =>
{
Debug.Log($"UDP Server, data: {NE.GetString(bytes)}. from {newUdpClient.Host}");
// echo effect
newUdpClient.ToData(bytes)
});
server.Open(new Host(ip, port));
Debug.Log("Netly UDP Server starting...");
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Return))
{
if (server.IsOpened)
{
if (string.IsNullOrEmpty(message) == false)
{
// (send) this data for all connected address
server.ToData(message);
print("data sent.");
}
}
}
}
} # client python
import socket
import threading
ip = "127.0.0.1"
port = 12000
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# receive data on background
def ReceiveDataOnBackground(m_socket, m_ip, m_port):
while True:
try:
data, addr = m_socket.recvfrom(2048) # max buffer size per data is 2048 bytes
print(f"message: {data} from {addr}")
except:
pass
# start background task for receive data from client.
tread = threading.Thread(target=ReceiveDataOnBackground, args=(sock, ip, port))
tread.start()
print("q -> quit application")
while True:
message = input("write message: ")
if (message == "q"):
exit()
# send data to the server.
if(len(message) > 0):
sock.sendto(message.encode(), (ip, port))
print('data sent.') It's working? |
Beta Was this translation helpful? Give feedback.
-
Not yet. If I become proficient in this library, I can provide practical suggestions |
Beta Was this translation helpful? Give feedback.
Well i think you wish use Unity as UdpServer and Pyhton as UdpClient.
using now:
NOTICE: First test my code without any modifications, after that: you can modify ip or whatever