I am creating a solution for data transfer to and from a python script and WinForm application. My current problem is that when the data is received and a received message is generated and sent back, the python script never sees it.
It was working before I introduced async functionality, but I wanted to use that to shut down the server/thread that was handling the server.
here is my server code (C#):
private void btnConnect_Click(object sender, EventArgs e)
{
InitializeUDP();
}
public void InitializeUDP()
{
//Create the server
endPoint = new IPEndPoint(IPAddress.Any, PORT);
udpClient = new UdpClient(endPoint);
ShowMsg("Waiting for a client...");
//Create the client end.
//Start listening
listenThread = new Thread(new ThreadStart(Listening));
listenThread.Start();
}
private void Listening()
{
byte[] resp;
//Listening loop
Task.Run(async () =>
{
while (true)
{
//Receive a message from a client
var data = await udpClient.ReceiveAsync();
string receivedMsg = Encoding.ASCII.GetString(data.Buffer);
//Show the message.
this.Invoke(new ShowMessageMethod(ShowMsg), new object[] { "Client:" receivedMsg });
//Send a response message
resp = Encoding.ASCII.GetBytes("Server:" receivedMsg);
udpClient.Send(resp, resp.Length, endPoint);
//Sleep for UI to work
Thread.Sleep(500);
}
});
}
private void ShowMsg(string msg)
{
this.tbTest.Invoke((MethodInvoker)(() => this.tbTest.Text = msg "\r\n"));
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
Stop();
}
private void Stop()
{
//Stop listening
ShowMsg("Server stopping...");
udpClient.Close();
ShowMsg("Server stopped.");
}
here is my client code (python):
import socket
msgFromClient = "Hello UDP Server"
bytesToSend = str.encode(msgFromClient)
serverAddressPort = ("127.0.0.1", 12345)
bufferSize = 1024
# Create a UDP socket at client side
UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# Send to server using created UDP socket
UDPClientSocket.sendto(bytesToSend, serverAddressPort)
msgFromServer = UDPClientSocket.recvfrom(bufferSize)
msg = "Message from Server {}".format(msgFromServer[0])
print(msg)
CodePudding user response:
You're sending a packet to address IPAddress.Any
and the server's port, instead of the client's IP address and port.
The client's IP address and port are stored in data.RemoteEndPoint
.
How to find this: notice that ReceiveAsync
returns a Task<UdpReceiveResult>
- UdpReceiveResult
is the "return type" of the task - await
waits for the task to complete and then gives you the UdpReceiveResult
. Then see that UdpReceiveResult
has a field called RemoteEndPoint
which is what you want.