How to receive UDP socket data in SignalR Hub C# - c#

I have created a hub in SignalR in my web project. In my hub class I want to receive udp data sent on port no 4001. Please suggest the code to receive data through udp socket. I tried to receive using the code as shown below but it gives error "System.Net.Sockets.SocketException: 'Only one usage of each socket address (protocol/network address/port) is normally permitted"
ClockHub.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace RealTimeClock.App_Code
{
public class ClockHub : Hub
{
public void getSocketData()
{
// Here I want to receive udp socket data on port 4001
// my code commented here did not work
//UdpClient receivingUdpClient = new UdpClient(11000);
//IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
//Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
//string UDP_Rx_Data= Encoding.ASCII.GetString rceiveBytes);
Clients.Caller.setTime(UDP_Rx_Data);
}
}
}

Related

Why is my Server TcpListener Working with Local Address but not with Public Address? - Exception: The requested address is not valid in its context

I wrote a server and a client program in C# using a TcpListener and a TcpClient and I want them to exchange a string. It works if both PCs are connected to the same network and if I use the local address of the server, but when the PCs are connected to a different network and I use a public address it gives me the following error:
Exception: System.Net.Sockets.SocketException (0x80004005): The requested address is not valid in its context
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at System.Net.Sockets.TcpListener.Start(Int32 backlog)
at System.Net.Sockets.TcpListener.Start()
at Server___Network_Class.Program.Main(String[] args) in D:\Server - Network Class\Program.cs:line 18
This error refers to line 18, which is myList.Start(); but I don't know why it throws this exception. I opened my router port and I set up correctly the Windows Firewall...
Here's the Server and Client code I wrote:
Server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Server___Network_Class {
class Program {
static void Main(string[] args) {
try {
IPAddress ipAddress = IPAddress.Parse("146.241.31.193"); //That's the public IP
//Initialize the listener
TcpListener myList = new TcpListener(ipAddress, 51328);
//Start listening the selected port
myList.Start();
Socket socket = myList.AcceptSocket();
ASCIIEncoding asen = new ASCIIEncoding();
socket.Send(asen.GetBytes("Can you read this?"));
socket.Close();
myList.Stop();
}
catch (Exception e) {
Console.WriteLine("Exception: " + e);
}
Console.ReadKey();
}
}
}
Client
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Client___Class_Network {
class Program {
static void Main(string[] args) {
try {
//Inizializzo il client
TcpClient client = new TcpClient();
//Cerco di connettermi al server
client.Connect("146.241.31.193", 51328); //IP and Port i want to connect to
//Stream sul quale inviare e ricevere i dati dal server
NetworkStream stream = client.GetStream();
Byte[] bytesRecived = new Byte[256];
int totBytesRecived = stream.Read(bytesRecived, 0, bytesRecived.Length);
String stringData = System.Text.Encoding.ASCII.GetString(bytesRecived, 0, totBytesRecived);
Console.Write(stringData);
client.Close();
}
catch (Exception e) {
Console.WriteLine("Exception: " + e);
}
Console.ReadKey();
}
}
}
Only the server program throws that exception, the client one seems working file...
Could you please help me out with this problem? I have (almost) searched all over the web but I couldn't find any useful answer.
Thanks in advance!
Is the public IP address really available at your Windows machine or only on the router?
Check if the public address shows up when running ipconfig in the Command line window. My guess is that you need to set up NAT port forwarding in the router and set the application to listen to the IP address your router gave to your Windows machine. Such an IP address typically starts with 10. or 192..
Try binding your server to the address 0.0.0.0. This way, it will listen to all your network cards (WiFi, Ethernet) without the need for any configuration.

C# - Can't receive UDP on second computer

I can send UDP messages from one computer to itself on a certain port but I can't send this messages from one computer to another in the same lan. I am pretty new to C# and I am also new to network programming so the solution is probably easy...
I have tried an example from Microsoft Docs and did only small changes. (names, etc.)
Both codes run as seperate programs.
//RECEIVE
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UDPListener
{
private const int listenPort = 11000;
private static void Listen()
{
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
try
{
while (true)
{
Console.WriteLine("Waiting for broadcast");
byte[] receivebytes = listener.Receive(ref groupEP);
Console.WriteLine(Encoding.ASCII.GetString(receivebytes, 0, receivebytes.Length));
}
}
catch (SocketException e)
{
Console.WriteLine(e);
}
finally
{
listener.Close();
}
}
public static void Main()
{
Listen();
}
}
//SEND
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Program
{
static void Main(string[] args)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//192.168.2.5 is the IP Address of the receiving computer
IPAddress broadcast = IPAddress.Parse("192.168.2.5");
byte[] bytestosend = Encoding.ASCII.GetBytes("Hi");
IPEndPoint ep = new IPEndPoint(broadcast, 11000);
socket.SendTo(bytestosend, ep);
Console.WriteLine("bytestosend were send");
}
}
The sending program tells me that the message was sent but the receiving program gives no output.
EDIT 1: The Ressource Manager said that on the receiving computer was no network activity while on the sending computer is actually sending something.
EDIT 2: I tried my applications in an other network and it worked fine. I did some research and I found that sometimes routers don't allow udp broadcasts through a subnet (or anything similar...). So I assume it might be my router. (unfortunately I can not access it's settings.) So I think the problem has resolved itself!

Why do I need two sockets in server application?

I am trying to learn socket programming in C#
By using google I found a lot of good tutorials and examples.
But here is my own code :
Sender application :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net; // socket library
using System.Net.Sockets; // socket library
namespace Sender
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter remote IP : ");
IPAddress ipAddress = IPAddress.Parse(Console.ReadLine());
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(ipAddress, 4444);
Console.Write("Enter text to send : ");
byte[] message = Encoding.ASCII.GetBytes(Console.ReadLine().ToString());
sender.Send(message);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.ReadKey();
} // main
} // main
} // main
Receiver application :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net; // socket library
using System.Net.Sockets; // socket library
namespace Listener
{
class Program
{
static void Main(string[] args)
{
IPAddress ipAddress = Dns.GetHostAddresses(Dns.GetHostName()).Where(address => address.AddressFamily == AddressFamily.InterNetwork).First();
Console.WriteLine("Listening on " + ipAddress.ToString() + " : 4444");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 4444);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(10);
Socket handler = listener.Accept();
byte[] bytes = new Byte[1024];
int bytesRec = handler.Receive(bytes);
Console.WriteLine(Encoding.ASCII.GetString(bytes, 0, bytesRec));
handler.Shutdown(SocketShutdown.Both);
handler.Close();
listener.Close();
Console.ReadKey();
} // main
} // main
} // main
The code works fine, but I want to know why do I need two sockets in server side? The first one is listener and the second one is handler. Is it possible to omit one of them so that the code become more simple?
By the way my code is based on these codes :
Synchronous Client Socket Example : https://learn.microsoft.com/en-us/dotnet/framework/network-programming/synchronous-client-socket-example
Synchronous Server Socket Example : https://learn.microsoft.com/en-us/dotnet/framework/network-programming/synchronous-server-socket-example
Also I am using Microsoft Visual C# 2008 Express Edition
The listener socket is listening for the incoming connections. If there were no handler socket, then there were no one to listen for parallel incoming connections until the communication with the client is over.
That's why Accept returns another socket, which is used for communication, and the listening socket continues waiting for incoming connections.
You can see it as a kind of weakly-typed objects: the Socket is responsible for both listening and communication roles, although it might be better to have different types for these two different tasks. But this behaviour reflects the traditional socket behaviour, so it remains as it is in order to be familiar to the people having background in network programming.
The more high-level API (TcpListener and TcpClient) makes a clear distinction between listening and communication roles.

Open TCP port using UDP?

I read something about using UDP to open ports. I can't find the original page I read but I did find this SO answer https://stackoverflow.com/a/1539394
I tried running this code. Perhaps I did something wrong? The idea (in link above) was Alice listens to port 5412, sends a UDP packet to bob from 5412 (the tcp port) to 5411. Bob (who doesn't listen) uses TCP port 5411 (the udp port) to connect to Alice 5412. I use the command line on bob to give alice IP address.
Did I do this wrong? When I run locally using my public IP address (and my network address but not 127.0.0.1) I get the exception A socket operation was attempted to an unreachable network. When I run it on Bob I get a connection timeout exception.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace TcpTest
{
class Program
{
static string localIp = "127.0.0.1";
static string remoteIP = ipaddr;
static void Main(string[] args)
{
//run remotely to connect to you using TCP
if (args.Count() > 0)
{
var t = new TcpClient(new IPEndPoint(IPAddress.Parse(localIp), 5411)); //Force port
t.Connect(args[0], 5412);
return;
}
//Run locally
//Bind TCP port
var l = new TcpListener(5412);
l.Start();
//Send UDP using the listening port to remote address/port
var u = new UdpClient(5412);
u.Connect(remoteIP, 5411);
var buf = new byte[10];
u.Send(buf, buf.Length);
//R
new Thread(SimulateRemote).Start();
//L
var c = l.AcceptTcpClient();
var af=c.Client.RemoteEndPoint;
}
static void SimulateRemote()
{
Thread.Sleep(500);
var t = new TcpClient(new IPEndPoint(IPAddress.Parse(localIp), 5411)); //Force port
t.Connect(myipaddr, 5412);
}
}
}
You can't do that.
TCP ports and UDP ports can't connect to each other. The packets you send from UdpClient.Send() have the Protocol field set to 0x11, the value for UDP, but the TCP stack only recognizes packets with Protocol set to 0x06, the value for TCP. It's part of the most-basic operation of an IP module. See RFC 791 if you want the details.

When to close a UDP socket

I have a client-server application that uses a UDP socket to send the data , the data only have to travel from client to server , and the server will always have the same IP. The only requirement is that I have to send messages about 10 messages per second
Currently I am doing it the following way :
public void SendData(byte[] packet)
{
IPEndPoint end_point = new IPEndPoint(serverIP, serverPort);
UdpClient udpChannel = new UdpClient(sourcePort);
udpChannel.Connect(end_point);
udpChannel.Send(packet, packet.Length);
udpChannel.Close();
}
The problem I have is that when I use the command "udpChannel.Close()" it takes 2-3 seconds to be performed when the server is not listening. (I've seen the same problem in: What is the drawback if I do not invoke the UdpClient.Close() method?)
My question would be, if I always send packets to the same IP address and port, is it necessary to connect the socket and close it after each send request?
The code I intend to use would be as follows:
UdpClient udpChannel;
public void SendData(byte[] packet)
{
udpChannel.Send(packet, packet.Length);
}
public void Initialize(IPAddress IP, int port)
{
IPEndPoint end_point = new IPEndPoint(serverIP, serverPort);
UdpClient udpChannel = new UdpClient(sourcePort);
udpChannel.Connect(end_point);
}
public void Exit()
{
udpChannel.Close();
}
Doing it this way, would it be necessary to do some checking in the "SendData" method before sending the data?
Is there any problem in the above code?
Thank you!
UDP is connectionless, calling udpChannel.Connect merely specifies a default host endpoint for use with the Send method. You do not need to close the client between sends, leaving it open will not leave any connections or listeners running between sends.
You shouldn't connect/close after each send request. When you start working - you connect to socket. And you can send data. You should close UdpClient when you do not want to send/recieve data, for example when you closing Form.
In your case you can check that udpClient != null when close/send client and you can use try/catch, for example:
try
{
udpClient.Send(sendBytes, sendBytes.Length);
}
catch (Exception exc)
{
// handle the error
}
Use try/catch when you connecting, because port may be busy or other problem with connection.
And look at UdpClient.SendAsync :)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Text;
using System.Net.Sockets;
using System;
using System.Net;
public class Server : MonoBehaviour
{
//int[] ports;
UdpClient udp; // Udp client
private void Start()
{
udp = new UdpClient(1234);
udp.BeginReceive(Receive, null);
}
void Send(string msg, IPEndPoint ipe)
{
UdpClient sC = new UdpClient(0);
byte[] m = Encoding.Unicode.GetBytes(msg);
sC.Send(m, msg.Length * sizeof(char), ipe);
Debug.Log("Sending: " + msg);
sC.Close();
}
void Receive(IAsyncResult ar)
{
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 0);
byte[] data = udp.EndReceive(ar, ref ipe);
string msg = Encoding.Unicode.GetString(data);
Debug.Log("Receiving: " + msg);
udp.BeginReceive(Receive, null);
}
}
At the Send() I use new UDP CLient and close it after every time. Its better, u can send and receive at the same time.

Categories