We have 2 Netduinos 2 plus, running the code bellow. The one has the IP 169.168.1.100, and the other has 169.168.1.101.
We get a connection, but we never receive any data. We have tryed making a connection to a windows computer, running a test program. In this scenario both Sever and Client works as expected.
When running the Sever and Client code on the same Netduino, and connecting to itself, everything works.
// ------------------------ Sever ----------------------------------------
public static void Main()
{
var networkAdapter = NetworkInterface.GetAllNetworkInterfaces()[0];
networkAdapter.EnableStaticIP("192.168.1.100", "255.255.255.0", "192.168.1.1");
(new Thread(Sever)).Start();
Thread.Sleep(Timeout.Infinite);
}
private static void Sever()
{
Debug.Print("Starting listener");
try
{
_receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_receiveSocket.Bind(new IPEndPoint(IPAddress.Any, 4543));
_receiveSocket.Listen(2);
while (true)
{
using (Socket commSocket = _receiveSocket.Accept())
{
Debug.Print("Connected");
try
{
while (!commSocket.Poll(10, SelectMode.SelectRead)) ;
int bytesSent = commSocket.Available;
if (bytesSent > 0)
{
byte[] bytes = new byte[bytesSent];
int bytesReceived = commSocket.Receive(bytes, bytesSent, SocketFlags.None);
if (bytesReceived == bytesSent)
{
Debug.Print(new string(Encoding.UTF8.GetChars(bytes)));
}
}
}
finally
{
commSocket.Close();
}
}
}
}
catch (Exception exception)
{
Debug.Print("Listen error: " + exception.Message + " stacktrace: " + exception.StackTrace);
}
}
// -------------- Client .-------------------------------
public static void Main()
{
var networkAdapter = NetworkInterface.GetAllNetworkInterfaces()[0];
networkAdapter.EnableStaticIP("192.168.1.101", "255.255.255.0", "192.168.1.1");
(new Thread(Client)).Start();
Thread.Sleep(Timeout.Infinite);
}
static void Client()
{
while (true)
{
using (var send = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
var destination = new IPEndPoint(IPAddress.Parse("192.168.1.100"), 4543);
byte[] buf = Encoding.UTF8.GetBytes("Hello World ");
try
{
send.Connect(destination);
send.Send(buf, buf.Length, SocketFlags.None);
}
catch(Exception e)
{
Debug.Print("Error");
}
finally
{
send.Close();
Debug.Print("Exit");
}
}
}