1
When I use socket.Accept()
I get a connected Socket, using the option socket.ExclusiveAddressUse = false
it is possible to associate (Bind
) another Socket to EndPoint
.
But when I use the function ReceiveFrom
in that second Socket I get the error:
A request to send or receive data was not allowed because the socket is not connected and (while sending on a socket datagram using a sendto call) not provided a address
I know this is possible with UDP, it would also be with TCP?
How can I make it work?
The client:
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(new IPEndPoint(IPAddress.Parse("127.0.22.33"), 31));
socket.Send(Encoding.ASCII.GetBytes("Teste Socket"));
socket.Dispose();
The server:
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.ExclusiveAddressUse = false;
socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.22.33"), 31));
socket.Listen(int.MaxValue);
Socket socket2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket2.ExclusiveAddressUse = false;
socket2.Bind(new IPEndPoint(IPAddress.Parse("0.0.0.0"), 31));
byte[] buffer = new byte[10240];
var EPCliente = socket.Accept().RemoteEndPoint;
socket2.ReceiveFrom(buffer,SocketFlags.None,ref EPCliente);
socket.Dispose();
socket2.Dispose();
Console.WriteLine(Encoding.ASCII.GetString(buffer));
For a TCP socket the method of receiving data would be Receive(), not Receivefrom(), the latter serves for UDP and other protocols without connection because you need to receive the packet and the sender at the same time, while in a TCP socket the remote side is set and does not change.
– epx
I suspected, I needed to have a reference to the sending socket before the connection. Surely internally there must be a connection token/ticket. I think this socket model is a mess, because it uses the same object for different protocols/algorithms/stacks. This is object orientation bad practice.
– user178974
And this
"0.0.0.0"
was just an example, no?– Leandro Angelo
I believe the API follows the BSD/Sockets conventions, which have this same character (use recvfrom for UDP, recv for TCP) and is obviously not object-oriented.
– epx
According to RFC 923
0.0.0.0
meanseste host
dot net interprets it to bequalquer rede que esta máquina estiver conectada
. But c# is object oriented, is the kind of thinglegado
that is used today, and no one will waste time remaking something that already works well (https://i.stack.Imgur.com/7moWY.jpg).– user178974
0.0.0.0
is equivalent toIPAddress.Any
– user178974