UDPClient in C# - c#

i use in UDPClient in c#. i invoke the receive function, but the when i am running the app. the program enter to eternity loop. Why is this phenomenon? Maybe because no data were available on this port? what can i do?
I write the following code:
UdpClient udpClient = new UdpClient(623);
try
{
udpClient.Connect("10.0.0.16", 623);
// Sends a message to the host to which you have connected.
Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");
udpClient.Send(sendBytes, sendBytes.Length);
// Sends a message to a different host using optional hostname and port parameters.
UdpClient udpClientB = new UdpClient();
udpClientB.Send(sendBytes, sendBytes.Length, "10.0.0.16", 623);
//IPEndPoint object will allow us to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
// Uses the IPEndPoint object to determine which of these two hosts responded.
Console.WriteLine("This is the message you received " +
returnData.ToString());
Console.WriteLine("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
udpClient.Close();
udpClientB.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
thanks

I suspect it's because of no data, but to test this, you could try implementing 'BeginRecieve' instead of recieve. MSDN has an example:
http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.beginreceive.aspx

Related

C# Broadcasting message on server to remote client

I'm trying to broadcast a message from server to a remote client, my problem is that I'm not able to receive the message on the client, the approach I'm currently playing with is as follows:
//Server
UdpClient udpServer = new UdpClient();
udpServer.Client.Bind(new IPEndPoint(IPAddress.Any, port));
var send = Task.Run(() =>
{
var to = new IPEndPoint(IPAddress.Broadcast, port);
while (true)
{
var response = gameWorld.GetStateJson();
var responseInBytes = Encoding.ASCII.GetBytes(response);
udpServer.SendAsync(responseInBytes, responseInBytes.Length, to);
Console.WriteLine(response);
gameWorld.Update();
}
});
send.Wait();
And for the client:
//Client
UdpClient receivingUdpClient = new UdpClient(8081);
while (true)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse("11.111.111.111"), 0);
try
{
byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine(returnData.ToString());
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
So the current client code works as expected, but only for my LAN (if I understand correctly), I'm not sure what should I change in order to be receiving the messages over the internet "globally", advice would be highly appreciated.
Side question: does the server code as is broadcast the data "globally" ? Or is it also for my LAN only?
EDIT: Is this somehow possible or do I have to send data to each client explicitly, even though they're the same for all

networkstream only sends data to the last IP connected to the server

i have a program that multiple clients would be able to connect to a server using a socket.
private void performConnect()
{
while (true)
{
if (myList.Pending())
{
thrd = thrd + 1;
tcpClient = myList.AcceptTcpClient();
IPEndPoint ipEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
string clientIP = ipEndPoint.Address.ToString();
nStream[thrd] = tcpClient.GetStream();
currentMsg = "\n New IP client found :" + clientIP;
recieve[thrd].Start();
this.Invoke(new rcvData(addNotification));
try
{
addToIPList(clientIP);
}
catch (InvalidOperationException exp)
{
Console.Error.WriteLine(exp.Message);
}
Thread.Sleep(1000);
}
}
}
then the server could send data (chat messages) to a chosen client, using this code.
private void sendData(String data)
{
IPAddress ipep =IPAddress.Parse(comboBox1.SelectedItem.ToString());
Socket server = new Socket(AddressFamily.InterNetwork , SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipept = new IPEndPoint( ipep, hostPort);
NetworkStream nStream = tcpClient.GetStream();
ASCIIEncoding asciidata = new ASCIIEncoding();
byte[] buffer = asciidata.GetBytes(data);
if (nStream.CanWrite)
{
nStream.Write(buffer, 0, buffer.Length);
nStream.Flush();
}
}
the problem is that whatever IP i choose from the combo box, the message i send would always be directed/sent to the last IP that connected to the server.. Please somebody help me find the error.. all help would be appreciated, thanks in advance!
That's because in sendData you perform
NetworkStream nStream = tcpClient.GetStream();
where tcpClient variable stores the last accepted connection. Instead of this, you should use your nStream[] array which stores all the connected streams.

Client-Server connection with sockets

I have a program that multiple clients would be able to connect to a server using a socket:
private void performConnect()
{
while (true)
{
if (myList.Pending())
{
thrd = thrd + 1;
tcpClient = myList.AcceptTcpClient();
IPEndPoint ipEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
string clientIP = ipEndPoint.Address.ToString();
nStream[thrd] = tcpClient.GetStream();
currentMsg = "\n New IP client found :" + clientIP;
recieve[thrd].Start();
this.Invoke(new rcvData(addNotification));
try
{
addToIPList(clientIP);
}
catch (InvalidOperationException exp)
{
Console.Error.WriteLine(exp.Message);
}
Thread.Sleep(1000);
}
}
}
then the server could send data (chat messages) to a chosen client, using this code.
private void sendData(String data)
{
IPAddress ipep =IPAddress.Parse(comboBox1.SelectedItem.ToString());
Socket server = new Socket(AddressFamily.InterNetwork , SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipept = new IPEndPoint( ipep, hostPort);
NetworkStream nStream = tcpClient.GetStream();
ASCIIEncoding asciidata = new ASCIIEncoding();
byte[] buffer = asciidata.GetBytes(data);
if (nStream.CanWrite)
{
nStream.Write(buffer, 0, buffer.Length);
nStream.Flush();
}
}
the problem is that whatever IP i choose from the combo box, the message i send would always be directed/sent to the last IP that connected to the server.. Please somebody pinpoint my error! all help would be appreciated.
Look at those lines:
IPAddress ipep =IPAddress.Parse(comboBox1.SelectedItem.ToString());
Socket server = new Socket(AddressFamily.InterNetwork , SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipept = new IPEndPoint( ipep, hostPort);
NetworkStream nStream = tcpClient.GetStream();
You are creating a new socket but you are sending the data to the socket stored in the variable tcpClient that is global (since it was not defined in the method), thus totally ignoring the IPEndPoint parsed from the combobox.
You should not create a new socket in order to send data to the clients. Instead, store all clients in a collection and retrieve the appropriate one based on the input of the combobox.

why is the UDPclient multicast not working?

public void send_multicast(string message)
{
UdpClient c = new UdpClient(10102);
Byte[] sendBytes = Encoding.ASCII.GetBytes(message);
IPAddress m_GrpAddr = IPAddress.Parse("224.0.0.1");
IPEndPoint ep = new IPEndPoint(m_GrpAddr,10102);
c.MulticastLoopback=true;
c.JoinMulticastGroup(m_GrpAddr);
c.Send(sendBytes,sendBytes.Length,ep);
Console.WriteLine(message);
}
public string recv_multicast()
{
Console.WriteLine("was here");
String strData = "";
//String Ret = "";
ASCIIEncoding ASCII = new ASCIIEncoding();
UdpClient c = new UdpClient(10101);
// Establish the communication endpoint.
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 10101);
IPAddress m_GrpAddr = IPAddress.Parse("224.0.0.1");
c.JoinMulticastGroup(m_GrpAddr);
Byte[] data = c.Receive(ref endpoint);
strData = ASCII.GetString(data);
//Ret += strData + "\n";
return strData;
}
is there anything wrong with the ports?
the recv method is getting blocked but is not receiving the message?
In wireshark I can see the message going from local addr port 10102 to 224.0.0.1 dest_port 0, but the recv is not getting the msg from the multicast addr.
BTW I am running both instances on the same computer.
reference : http://msdn.microsoft.com/en-us/library/ekd1t784.aspx
**Got the solution:In send routine
IPEndPoint ep = new IPEndPoint(m_GrpAddr,10102);
should be
IPEndPoint ep = new IPEndPoint(m_GrpAddr,10101);
the port of receiving**
You need to enable multicast loopback in order to recieve packets sent by yourself.
http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.multicastloopback.aspx
You should use JoinMulticastGroup on the server side as well as the client side. If that fails, you can also try using Wireshark (google it) to see if the packets are actually sent.

Get client IP from UDP packages received with UdpClient

I am developing an action multiplayer game with the help of the System.Net.Sockets.UdpClient class.
It's for two players, so one should open a server and wait for incoming connections. The other player inputs the host IP and tries to send a "ping", to make sure a connection is possible and there is an open server. The host then responds with a "pong".
Once the game is running, both have to send udp messages to each other, so they both need the opponents ip address.
Of course the server could also input the clients IP, but that seems unneccessary to me.
How can I get the clients IP from the udp package when the "ping" message is received?
Here is my receiving code (server waiting for ping):
private void ListenForPing()
{
while (!closeEverything)
{
var deserializer = new ASCIIEncoding();
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] recData = udp.Receive(ref anyIP);
string ping = deserializer.GetString(recData);
if (ping == "ping")
{
Console.WriteLine("Ping received.");
InvokePingReceiveEvent();
}
}
}
In your example, when a client connects, the anyIP IPEndPoint object will contain the address and port of the client connection.
private void ListenForPing()
{
while (!closeEverything)
{
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] recData = udp.Receive(ref anyIP);
string ping = Encoding.ASCII.GetString(recData);
if (ping == "ping")
{
Console.WriteLine("Ping received.");
Console.WriteLine("Ping was sent from " + anyIP.Address.ToString() +
" on their port number " + anyIP.Port.ToString());
InvokePingReceiveEvent();
}
}
}
http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.receive.aspx

Categories

Resources