How to use dynamic ports with the Socket class? - c#

I am just learing about networking and I belive there's something called "dynamic ports".
I can't get my head around that, how would I implement a server, that uses dynamic ports? When setting up a socket, I'll have to bind to a specific port just like:
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
socket.Bind(endPoint);
socket.Listen(10);
using (Socket handler = socket.Accept())
{
/* ... */
}
}
I needed to definly set the port I wantet to listen on (1234).
As far as I understand dynamic ports, a client sends a request to a random port and the server somehow dermines which application will get those request and make a response.
How would the client say
I would like my request to be responded my the "MyCustomService01" application?
Can someone please clarify and give some sample code?

socket is your listener, that despatches onto ephemeral ports; if you look carefully at handler, in particular at .LocalEndPoint and .RemoteEndPoint, you should find it is already configured as a dynamic port. Basically, you shouldn't have to do anything special here - just communicate via handler.

Related

C# Convert from IPEndPoint to Socket

I have a server which works fine. But I think the way I am passing strings from a server to client is not the right way.
This is my current approach in server.
foreach (Socket _connectedUsers in clientSockets)
{
byte[] data = Encoding.UTF32.GetBytes("Text");
Socket socket = (Socket)_connectedUsers;
socket.Send(data);
}
In this approach it is sending string to all connected clients. But I want to be able to specify particular socket and send it to one unique connected client.
I know that I can identify IP and PORT of any connected socket by using this function:
IPEndPoint remoteIpEndPoint = current.RemoteEndPoint as IPEndPoint;
This function allows me to see what IP and port number current socket has.
But lets say I get entire list of connected sockets and get them as 'IPEndPoint' list. How can I convert it into socket to do something like this?
IPEndPoint remoteIpEndPoint = current.RemoteEndPoint as IPEndPoint;
Socket SendToSocket = remoteIpEndPoint as Socket; //I know this is wrong.. How can I convert it to socket?
byte[] data = Encoding.ASCII.GetBytes("Server can Hear you");
SendToSocket.Send(data);
How can I convert IPEndPoint or string with IP and Port or anything else into Socket?
I think I explained my question in very detail.
If you have any other suggestions or techniques how I could make this possible, please help. :)
Also it is worth to mention why I don't want to use 'foreach', because if I will stream my web camera in my app, I don't want to stream to everyone because 'foreach' is streaming for everyone. This is why I need to specify unique socket to avoid streaming and reduce traffic in other clients when they are not supposed to receive anything.

C# TCP Socket Communicator - handle special messages between client and server

I want to learn about socket communication so I decided to try to write WP 8.1 text communicator. It is based on TCP sockets. I almost managed to finish it, but I am searching for improvemenets.
What is worth mentioning I use a socket server between phones (console application), to avoid problems with private ip addresses. It contains information about all connected users and forwards messages to clients (for instance user A sends message to user B, so firstly message goes to server and server forward it to destination address).
The problem appeared when i realized that I need to send special messages from server to client and vice versa (for example when two clients want to have conversation, they send request to server, so it knows where to forward messages).
This is my connection listener method from server application
private void ConnectionListener()
{
IPEndPoint localDataEndPoint = new IPEndPoint(IPAddress.Parse(LocalIpAddress), 1234);
IPEndPoint localMessageEndPoint = new IPEndPoint(IPAddress.Parse(LocalIpAddress), 4321);
Socket dataConnectionListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket messageConnectionListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
dataConnectionListener.Bind(localDataEndPoint);
dataConnectionListener.Listen(100);
messageConnectionListener.Bind(localMessageEndPoint);
messageConnectionListener.Listen(100);
while (true)
{
TcpSocket.clientDone.Reset();
IAsyncResult tmp1 = dataConnectionListener.BeginAccept(ConnectionCallback, null);
IAsyncResult tmp2 = messageConnectionListener.BeginAccept(ConnectionCallback, null);
TcpSocket.clientDone.WaitOne();
Socket dataSocket = dataConnectionListener.EndAccept(tmp1);
Socket messageSocket = messageConnectionListener.EndAccept(tmp2);
TcpSocket tmpTcpSocket = new TcpSocket(dataSocket, messageSocket);
tmpTcpSocket.Start();
connectedUsersSockets.Add(tmpTcpSocket);
UpdateConnectedUserList();
}
}
catch (Exception ex)
{
Log.E("Connection listener ran into an exception", ex);
}
}
As you can see I have created two TCP sockets to liesten on different ports. dataSocket is for normal messages and messageSocket is for special messages (sorry for confusing names, I have to refractor code).
On client side it works the same way: there are two different socket to communicate with and through the server.
I wanted to avoid managing two sockets rather then one. But the only way I can imagine is that on every received message server would have to check if it's special (and handle it in special way) or just send to client.
The question: Is there a better way to manage these special messages?
Thanks to all in advance!
P.S.
Sorry for my poor english, it's not my native language

C# TCP Socket.Receive issue when reusing socket

preface:
I've been stumped on this for awhile now and am not having much luck finding what I need.
I have a C# (.NET 3.5) Service. One thread acts as an asynchronous listener for incoming TCP connections. When data comes in I spawn off a new worker thread to handle the data, and sends an acknowledgement back.
On a second thread in the same service we send commands out, until today it would gather information from the data base, build a new socket, connect then ship the command and I'm using the Socket.Receive to invoke blocking and wait for a response (or until a timeout occurrs).
Everything has been working great until a new client has a need to send data to us so fast (5-10 second intervals) that we can no longer open a new socket to get a command through. So I started looking into when a command needs to be sent that the "listener" thread has a client connected. If that client is connected currently use that socket instead of creating a new one.
Issue:
I'm to the point where I can send my command back on the same socket the listener receives, but when the client sends data back as the response it takes twice for the Socket.Receive method to actually fire thinking it received data. The first time it gets into my listener class, the 2nd time, in my command class where I actually want it to be.
Question:
Is there some option or something I need to do before calling my Socket.Receive method to ensure the data gets to the correct place?
In my listener class I have a list of objects "CSocketPacket"
public class CSocketPacket
{
public CSocketPacket(System.Net.Sockets.Socket socket)
{
thisSocket = socket;
this.IpAddress =
((System.Net.IPEndPoint)socket.RemoteEndPoint).Address.ToString();
}
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[BUFFER_SIZE];
public string IpAddress; //Use this to search for the socket
}
Then when I send a command I'm creating a new tcp socket object:
client = new Socket(
AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(
IPAddress.Parse(Strings.Trim(ipAddress)), port);
IPEndPoint LocalIp = new IPEndPoint(IPAddress.Parse(
System.Configuration.ConfigurationManager.AppSettings["SourceIP"]), port);
then I'm looking into my listener class list to see if that socket is connected:
if (listener.SocketExists(ipAddress))
{
// set the client socket in this class to the
// instance of the socket from the listener class
SocketIndex = listener.FindSocketInList(ipAddress);
if (SocketIndex != -1)
{
// might need to figure out how to avoid copying the socket
// to a new variable ???
client = listener.ConnectedSockets[SocketIndex].thisSocket;
SocketBeingReUsed = true;
}
}
else
{
// try to connect to the client
client.Connect(ep);
}
finally I go through my steps of sending and receiving
if (client.Connected)
{
if (client.Poll(1000, SelectMode.SelectWrite))
{
int sentAmount = Send(ref client);
client.ReceiveTimeout = 90000; //90 seconds
returnData = ReceiveData(ref client, sentAmount);
}
}
everything works up to the point in my ReceiveData(ref client, sentAmount) method where I call the Socket.Receive(data, total, Socket.ReceiveBufferSize, SocketFlags.None); method.
I've been using a tool called Hercules to test sending/receiving packets across two machines on my home network.
Does anyone have any ideas of what I can do to solve this? I do apologize for such a lengthy question but I want to try to give as much info and not paste my entire project. I'm up for any suggestions.
Disclaimer: I wrote this code approx 3 years ago, so I'm pry doing things I shouldn't be I'm sure :P
Thanks to all who read this.
Sincerely,
Chris
OK, so now I'm following along! Given what you've said in the comments above, then the way to solve the problem is to have a single class/thread that reads from the socket (which is the correct way to read from sockets anyway) and then it will coordinate which class gets the data. I think it might work a little like the Command Design Pattern.

Help me to choose Socket or TCPListener

I read 2 C# chat source code & I see a problem:
One source uses Socket class:
private void StartToListen(object sender , DoWorkEventArgs e)
{
this.listenerSocket = new Socket(AddressFamily.InterNetwork , SocketType.Stream , ProtocolType.Tcp);
this.listenerSocket.Bind(new IPEndPoint(this.serverIP , this.serverPort));
this.listenerSocket.Listen(200);
while ( true )
this.CreateNewClientManager(this.listenerSocket.Accept());
}
And other one uses TcpListener class:
server = new TcpListener(portNumber);
logger.Info("Server starts");
while (true)
{
server.Start();
if (server.Pending())
{
TcpClient connection = server.AcceptTcpClient();
logger.Info("Connection made");
BackForth BF = new BackForth(connection);
}
}
Please help me to choose the one. I should use Socket class or TcpListener class. Socket connection is TCP or UDP? Thanks.
UDP is connectionless, but can have a fake connection enforced at both ends on the socket objects. TCP is a stream protocol (what you send will be received in chunks on the other end), and additionally creates endpoint sockets for each accepted socket connection (the main listening socket is left untouched, although you'd probably need to call listen() again). UDP uses datagrams, chunks of data which are received whole on the other side (unless the size is bigger than the MTU, but that's a different story).
It looks to me like these two pieces of code are both using TCP, and so as the underlying protocol is the same, they should be completely compatible with each other. It looks as if you should use the second bit of code since it's higher level, but only the server can really use this, the client needs a different bit of code since it doesn't listen, it connects... If you can find the 'connecting' code at the same level of abstraction, use that.

Why UDP socket subscribed to a multicast group is picking up a non-multicast message?

Overview: I have set up a server and a client, where both attempt discovery of each other using UDP. When the server starts up it sends a multicast message (239.1.1.1) that it is alive. When the client starts up it sends a multicast message (239.1.1.2) that it is alive. Both server and client are subscribed to each other's multicast messages to receive their transmissions. This way, regardless of which application (server or client) starts up first, one or the other will be notified of their existence.
On the client side I do the following:
Set up a listening socket to subscribe to and receive server originated multicast messages.
Set up a receiving socket to receive server responses to client's multicast
message per #3 below.
Send a muticast message (for server to receive and respond to) that client is running.
Receive server response to clients multicast message sent in #3.
Question: Everything is working fine, except that both receiving sockets end up getting the server's (non-multicast) response to the client. I am not clear if this is expected behavior or not. Can I reduce the two receiving sockets to one? #1 is subscribed to the server's multicast and #2 is simply listening for a direct transmission from the server on the same port (non-multicast message from server). Can I safely remove the second receiving socket?
See source code below (I removed exception handling for simpler code presentation).
Client code:
// 1. Set up a socket and asynchronously listen for server startup multicasts.
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
listenSocket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, 1);
listenSocket.Bind(new IPEndPoint(IPAddress.Any, 50000));
listenSocket.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.AddMembership,
new MulticastOption(IPAddress.Parse("239.1.1.1")));
EndPoint clientEndPoint = new IPEndPoint(0, 0);
listenSocket.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length,
SocketFlags.None, ref clientEndPoint,
new AsyncCallback(OnServerMessageReceived), (object)this);
// 2. Set up socket to receive the server's response to client's multicast.
Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
receiveSocket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, 1);
receiveSocket.Bind(new IPEndPoint(IPAddress.Any, 50000));
receiveSocket.ReceiveTimeout = 3000; // Timeout after 3 seconds.
// 3. Send a multicast message for server to respond to.
Socket sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
EndPoint multicastEndPoint = new IPEndPoint(IPAddress.Parse("239.1.1.2"), 50000);
sendSocket.SendTo(packet, packet.Length, SocketFlags.None, multicastEndPoint);
// 4. Wait for server to respond to the multicast message (timeout = 3 seconds).
byte[] receiveBuff = new byte[2048];
EndPoint serverEndPoint = new IPEndPoint(0, 0);
int bytesRead = receiveSocket.ReceiveFrom(receiveBuff, ref serverEndPoint);
Server code:
// Receive multicast message sent from client (in asynchronous callback method).
EndPoint clientEndPoint = new IPEndPoint(0, 0);
int bytesRead = listenSocket.EndReceiveFrom(asyncResult, ref clientEndPoint);
// Send response back to the client (change port to 50000).
EndPoint destination = new IPEndPoint((clientEndPoint as IPEndPoint).Address,
50000);
Socket responseSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
responseSocket.SendTo(response, response.Length, SocketFlags.None, destination);
The answer to your question is "Yes, this is expected behaviour". You don't need to open a seperate socket to recieve unicast packets on the same port.
PS
It seems like overkill to have your servers join a multicast group to listen for new clients - you could just have the servers regularly transmit a beacon to the client multicast address saying "I am here" (say, once every 30 seconds).
receiveSocket.Bind(new IPEndPoint(IPAddress.Any, 50000));
Your receive sockets are binding to ANY address, which means they will receive unicast, broadcast and multicast traffic. You can bind to an interface address to just receive unicast traffic, and you can bind just to the multicast group to only receive multicast traffic.
When sending a UDP datagram you can specify the destination address which may be multicast or unicast. You can therefore reduce both the server and client code to one socket each.
Whilst I'm not sure it's addressing your issue, I would expect both client and server to talk on the same IP multicast address (e.g. 239.1.1.1). At the moment it looks like you've given the client and server one address each, and what happens if/when you introduce a new client ?
Better option would be to use a service discovery protocol like Bonjour or Avahi than rolling your own, as they have solved a lot of problems already.

Categories

Resources