I'm trying to write a console application that takes a request (size is to be 18 bytes), and then send something (size of 7 bytes) back to the client. I for the life of me can't seem to get this to work. I can receive the data fine, but the data I send back never gets to the client.
Here is my code
static void Main(string[] args)
{
// Data to return
byte[] ret = { 0xfe, 0xfd, 0x09, 0x00, 0x00, 0x00, 0x00 };
// tell the user that we are waiting
Console.WriteLine("Waiting for UDP Connection...");
// Create a new socket to listen from
Socket Skt = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Skt.EnableBroadcast = true;
Skt.Bind(new IPEndPoint(IPAddress.Loopback, 27900));
try
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = new byte[48];
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint senderRemote = (EndPoint)sender;
Skt.ReceiveFrom(receiveBytes, ref senderRemote);
string returnData = Encoding.UTF8.GetString(receiveBytes).Trim();
Console.WriteLine("This is the message you received " + returnData.ToString());
// Sent return data
int sent = Skt.SendTo(ret, senderRemote);
Console.WriteLine("Sent {0} bytes back", sent);
Skt.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.ReadLine();
}
Anyone give me some pointers please?
Without also seeing your client code it's difficult to be sure where the problem might lie. I can give you a working solution using the network library networkcomms.net though. The code for the server would be as follows:
And for the client:
You will obviously need to download the NetworkCommsDotNet DLL from the website so that you can add it in the 'using NetworkCommsDotNet' reference. Also see the server IP address in the client example is currently "127.0.0.1", this should work if you run both the server and client on the same machine. For more information checkout the getting started or how to create a client server application articles.
Here is the sample code i have modified and you can see you can receive and send from this sample. Method Test is acting as client which can be a different process now i have made it in different thread for simulation.