In .NET CF on a Windows CE 5.0 based POS device, if no connection (GPRS/WiFi) is available, when i try to connect my socket object i don't get any exceptions, even after it, when i try to send bytes to somewhere by Socket.SentTo() method i don't get any exceptions too! And even the returned value indicating the size of totally sent bytes is correct! what's the matter? how can i ensure of the health of the operations?
pieces of my code:
Socket m_socClient = new Socket(
AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAdd = IPAddress.Parse("192.168.7.80");
IPEndPoint remoteEP = new IPEndPoint(ipAdd, 2415);
m_socClient.Connect(remoteEP); // No exception!
// why works?
int iSent = m_socClient.SendTo(byData, byData.Length,
SocketFlags.None, remoteEP);
Few suggestions:
Check the Connected property of the connection
I understand SendTo is more suited for connectionless protocols, and Send() is better suited for Connection-oriented protocols like TCP.
Send() (and I expect SendTo()) may have no effect if there is no data to send. Have you checked there is data?
Related
I'm trying to make two applications. One will be sending data to a specific udp port, and the other will be reading it.
I am having 2 problems:
when running on the same machine, I get an error: "Only one usage
of each socket address (protocol/network address/port) is normally
permitted" so I need to figure out how to test it if I cannot have
multiple socket connections at the same port.
when I tried using
an internal ip of another computer within my network, I did not get
any reading at all.
server:
private Socket sock;
private const int PORT = 5000;
public void start()
{
sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.ReceiveTimeout = 1;// seconds
sock.SendTimeout = 1;// seconds
IPEndPoint iep = new IPEndPoint(IPAddress.Any, PORT);
EndPoint ep = (EndPoint)iep;
sock.Bind(iep);
MulticastView view_obj = new MulticastView();
while(true)
{
try
{
if (sock.Connected)
{
sock.Send(Serializer.ObjectToByteArray(view_obj));
}
}catch(Exception ex){
Console.WriteLine(ex);
}
Thread.Sleep(1000); // milliseconds
}
}
client:
IPAddress ip = IPAddress.Parse("127.0.0.1");
IPEndPoint iep = new IPEndPoint(ip, PORT);
EndPoint ep = (EndPoint)iep;
UdpClient client = new UdpClient(PORT);
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
// or using: Byte[] receiveBytes = client.Receive(ref ep);
Byte[] receiveBytes = client.Receive(ref RemoteIpEndPoint);
MulticastView view;
view = (MulticastView)Serializer.ByteArrayToObject(receiveBytes);
Note that I need separate apps (on separate processes).
You can't have 2 separate sockets open on the same IP address / port. Each IP/Port is a unique mailbox, so to speak. (Technically, it is possible to have 2 processes attached to the same socket, under certain circumstances, but that isn't relevant to your problem). The rule is simple, but the workarounds are several.
I would ask if the client really needs to have a standard port number. Normally, UDP/TCP clients just use a random socket and communicate with the server. The server is usually the only side of the connection that needs a standard, fixed port. The UdpClient.Receive() method will populate the IPEndPoint with the ip/port of the sender of the packet so that you can reply to it.
Either don't bind to IPAddress.Any (that causes it to bind to all interfaces). Replace the Any with a specific IP address (one machine can have multiple if you setup IP aliasing or multiple adapters), or simpler, change the port number of the client to differ from the server. You should be able to bind one end to the primary ethernet interface IP address, and bind the client to the loopback (127.0.0.1) address.
Even though this is an old question, I think it would be good to point out an exception to the one port rule.
If you are using multicast (which is UDP to a multicast address), you can set the SO_REUSEADDR option to use the port for multiple sockets.
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
I have several LANs(10.0.0.x) connected to a WAN(192.168.1.x). Each through a router that allows a network directed broadcast. This is to allow the devices in the LANs to be discovered by devices on the WAN.
I can send a broadcast on the LAN(10.0.0.255) and receive it on my socket. But when I move to the WAN I can see it in wireshark, but not my socket. I other words I have a device with address 10.0.0.1 sending the same message to 192.168.1.255 through a gateway but my socket is not receiving it. When this happens the source address is the address of the router. Here is the code for my socket:
udpSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
//Assign the any IP of the machine and listen on port number 5000
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 5000);
//Bind this address to the server
udpSocket.Bind(ipEndPoint);
IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 5000);
//The epSender identifies the incoming clients
EndPoint epSender = (EndPoint)ipeSender;
//Start receiving data
udpSocket.BeginReceiveFrom(byteData, 0, byteData.Length,
SocketFlags.None, ref epSender, new AsyncCallback(ReceiveAnnounce), epSender);
I have a wireshark trace for each message but I'm not sure the best way to post it. Thanks.
Do you understand that UDP provides no guarantee that a packet will be received? (TCP uses a client to server connection) and that packets are broadcast to a 'multicast group' (this resembles an IP-address but must be in the range 224.0.0.0 to 239.255.255.255) rather than to an IP.
Your use of IPAddress.Any tells it to use all network interfaces, but you never tell it which multicast group to use, I've never done this in C# myself, however it appears you want to add this line of code before your BeginReceiveFrom;
udpSocket.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.AddMembership,new MulticastOption(TARGET_IP));
You should replace TARGET_IP with the address of your multicast group you wish to listen on.
I took that line of code from this site; http://osix.net/modules/article/?id=409
Can I send and receive UDP datagrams on same socket,I am using for TCP communication.There exist multimedia communication in my application for which I have to use UDP for communication.If i create a new socket it threw an exception for properties of LingerState and NoDelay.When I Assigns the Old Socket Instance to other Socket variable it doesn't Allow me to change the properties as most of the properties are read Only.I have to Send data in the TCP connected Area.
*Code *
Socket SendingSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint Endp = new IPEndPoint(IPAddress.Parse("192.168.3.233"), port);
SendingSocket.Bind(Endp);
while (SendingSocket.Connected)
{
string Message = "Testing Message Sending Over UDP"; ASCIIEncoding Encode = new ASCIIEncoding();
byte[] MessageBytes = Encode.GetBytes(Message);
SendingSocket.SendTo(MessageBytes, 0, MessageBytes.Length, SocketFlags.None, Endp); }'
Hard to tell from that code fragment but possibly you do not need the SendingSocket.Bind(Endp) since your SendingSocket.SendTo also includes the IP end point. Also try simply
SendingSocket.SendTo(MessageBytes, Endp);
No. You can not use the same socket for both TCP and UDP. A socket is bound to only one protocol.
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.