Main Site Documentation

SocketException


#1

Hi! I’m working on a web client. Here is the code:


using System.Net;
using System.Net.Sockets;
using System.Text;
using Microsoft.SPOT;
using System.Threading;
using System;

namespace EPI.Net
{
    public class EfficientPutRequest
    {
        #region MysSettings        
        static string _server;
        static int httpPort;
        static string _name;
        static string _namespace = "http://tempuri.org/";
        static string _event = "CrearteEvent";
        #endregion

        public static Socket connection;


        public EfficientPutRequest(string uri)
        {
            Uri siteUri = new Uri(uri);
            _server = siteUri.Host;
            _name = siteUri.AbsolutePath;
            httpPort = siteUri.Port;
            connection = Connect(_server, 5000);
        }

        static Socket Connect(string host, int timeout)
        {
            IPHostEntry hostEntry = Dns.GetHostEntry(host);

            IPAddress hostAddress = hostEntry.AddressList[0];
            IPEndPoint remoteEndPoint = new IPEndPoint(hostAddress, httpPort);

            var connection = new Socket(AddressFamily.InterNetwork,  SocketType.Stream, ProtocolType.Tcp);
            connection.Connect(remoteEndPoint);
            connection.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
            connection.SendTimeout = timeout;
            return connection;
        }

        public void SendRequest(System.DateTime timestamp, string args)
        {
            Socket s = connection;
            const string CRLF = "\r\n";

            string content =
                "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                "<s:Body>" +
                "<" + _event + " xmlns=\"" + _namespace + "\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                "<timestamp>" + timestamp.ToString("yyyy-MM-ddTHH:mm:ss") + "</timestamp>" +
                "<Args>" + args + "</Args>" +
                "</" + _event + ">" +
                "</s:Body>" +
                "</s:Envelope>";
            byte[] contentBuffer = Encoding.UTF8.GetBytes(content);

            var requestLine =
                "POST " + _name + " HTTP/1.1" + CRLF;
            byte[] requestLineBuffer = Encoding.UTF8.GetBytes(requestLine);

            var headers =
                "Content-Type: text/xml; charset=utf-8" + CRLF +
                "SOAPAction: \"" + _namespace + _event + "\"" + CRLF +
                "Host: " + _server + CRLF +
                "Content-Length: " + contentBuffer.Length + CRLF +
                "Expect: 100-continue" + CRLF +
                "Accept-Encoding: gzip, deflate" + CRLF + CRLF;
            byte[] headersBuffer = Encoding.UTF8.GetBytes(headers);
            try
            {
                s.Send(requestLineBuffer);
                Thread.Sleep(100);
                s.Send(headersBuffer);
                Thread.Sleep(100);
                s.Send(contentBuffer);
                Thread.Sleep(100);

                s.Close();
                connection.Close();
            }
        }
    }
}

I’m using this code in order to test client:

using System;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using GHIElectronics.NETMF.FEZ;
using EPI.Net;

namespace FEZ_Cobra_Console_Application1
{
    public class Program
    {
        public static string endPoint = "http://192.*********/webservice.asmx";
        public static int i = 1;
        public static void Main()
        {
            while (true)
            {
                EfficientPutRequest Servicio = new EfficientPutRequest(endPoint);
                Servicio.SendRequest(System.DateTime.Now, 17, 17, 0, "");
                Debug.Print(i.ToString() + " sent");
                i++;
                Thread.Sleep(1000);
            }
        }

    }
}

Codeworks OK in emulator and in NetDuino+, but when I run it on my FezCobra, it gives socket error after sending about 15 messages. Here the error: http://img403.imageshack.us/img403/4320/sinttulotj.png

Can anyone help me???

PD: WebService is working OK, because of it does with emulator, NetDuino and a WindowsForms app.


#2

did you setup networ on device(IP, mask, gateway, DNS…) with MFDeploy?


#3

Yes I do, I’ve set up:
[ol]Static IP address
Subnet Mask
Default Gateway
MAC Address (the same that comes by deffault)
DNS Primary Address[/ol]
No DNS Secondary Address (0.0.0.0)
DHCP Disabled.

Around first 15 packets are sent without problem.


#4

now I see Im miss that info…
Please be shure that AFTER each creating Socket you also CLOSE it!!! You can’t leave Socket opened. This is reason that you receiving errors…


#5

Socket error 10035:

Resource temporarily unavailable.

This error is returned from operations on nonblocking sockets that cannot be completed immediately, for example recv when no data is queued to be read from the socket. It is a nonfatal error, and the operation should be retried later. It is normal for WSAEWOULDBLOCK to be reported as the result from calling connect on a nonblocking SOCK_STREAM socket, since some time must elapse for the connection to be established.

#6

I’ve tried closing connection after sending packets and happens the same.

Sometimes I have 10060 error: http://img4.imageshack.us/img4/8158/sinttuloanx.png


#7

For socket error codes look here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx


#8

This is a sample for Pachube (not mine) and neither works, after some sending I get the exception. In this case socket are closed:

using System;
using System.Threading;

using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;

using GHIElectronics.NETMF.FEZ;

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;

public class HelloPachubeSockets
{
    public static void Main()
    {
        const string apiKey = "***********************DNRH0MdAH5ZCsee5jmKM";
        const string feedId = "352***";
        const int samplingPeriod = 10000;   // 10 seconds

        const double maxVoltage = 3.3;
        const int maxAdcValue = 1023;

        var voltagePort = 10;
        var lowPort = 8;
        var highPort = 9;

        Socket connection = null;

        while (true)   // main loop
        {
            WaitUntilNextPeriod(samplingPeriod);

            Debug.Print("time: " + DateTime.Now);
            //Debug.Print("memory available: " + Debug.GC(true));

            if (connection == null)   // create connection
            {
                try
                {
                    connection = Connect("api.pachube.com",
                        samplingPeriod / 2);
                }
                catch
                {
                    Debug.Print("connection error");
                }
            }

            if (connection != null)
            {
                try
                {
                    int rawValue = voltagePort;
                    double value = (rawValue * maxVoltage) / maxAdcValue;
                    string sample = "voltage," + value.ToString("f");
                    Debug.Print("new sample: " + sample);
                    SendRequest(connection, apiKey, feedId, sample);
                }
                catch (SocketException)
                {
                    connection.Close();
                    connection = null;
                }
            }
        }
    }

    static Socket Connect(string host, int timeout)
    {
        // look up host's domain name, to find IP address(es)
        IPHostEntry hostEntry = Dns.GetHostEntry(host);
        // extract a returned address
        IPAddress hostAddress = hostEntry.AddressList[0];
        IPEndPoint remoteEndPoint = new IPEndPoint(hostAddress, 80);

        // connect!
        Debug.Print("connect...");
        var connection = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);
        connection.Connect(remoteEndPoint);
        connection.SetSocketOption(SocketOptionLevel.Tcp,
            SocketOptionName.NoDelay, true);
        connection.SendTimeout = timeout;
        return connection;
    }

    static void SendRequest(Socket s, string apiKey, string feedId,
        string content)
    {
        byte[] contentBuffer = Encoding.UTF8.GetBytes(content);
        const string CRLF = "\r\n";
        var requestLine =
            "PUT /v2/feeds/" + feedId + ".csv HTTP/1.1" + CRLF;
        byte[] requestLineBuffer = Encoding.UTF8.GetBytes(requestLine);
        var headers =
            "Host: api.pachube.com" + CRLF +
            "X-PachubeApiKey: " + apiKey + CRLF +
            "Content-Type: text/csv" + CRLF +
            "Content-Length: " + contentBuffer.Length + CRLF +
            CRLF;
        byte[] headersBuffer = Encoding.UTF8.GetBytes(headers);
        s.Send(requestLineBuffer);
        s.Send(headersBuffer);
        s.Send(contentBuffer);
    }

    static void WaitUntilNextPeriod(int period)
    {
        long now = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
        var offset = (int)(now % period);
        int delay = period - offset;
        Debug.Print("sleep for " + delay + " ms\r\n");
        Thread.Sleep(delay);
    }
}


#9

Closing socket seems to be needed. It works OK in emulator, but no way with FezCobra. Any idea??

PD: I’ve updated code in my question.


#10

There si linger option that needs to be set to -2 IIRC. Search the forum for “linger”


#11

Using:

connection.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.Linger, new byte[] { 0, 0, 0, 0 });

All seems to work OK. Lots of thanks!!!


#12

I also have a timer in my app, but after some time. VS show me this:

[quote]GC: 364msec 385548 bytes used, 12655500 bytes available
Type 0F (STRING ): 38136 bytes
Type 11 (CLASS ): 78444 bytes
Type 12 (VALUETYPE ): 4788 bytes
Type 13 (SZARRAY ): 213480 bytes
Type 15 (FREEBLOCK ): 12655500 bytes
Type 16 (CACHEDBLOCK ): 216 bytes
Type 17 (ASSEMBLY ): 22248 bytes
Type 18 (WEAKCLASS ): 144 bytes
Type 19 (REFLECTION ): 24 bytes
Type 1B (DELEGATE_HEAD ): 504 bytes
Type 1D (OBJECT_TO_EVENT ): 408 bytes
Type 1E (BINARY_BLOB_HEAD ): 192 bytes
Type 1F (THREAD ): 3072 bytes
Type 20 (SUBTHREAD ): 240 bytes
Type 21 (STACK_FRAME ): 3084 bytes
Type 22 (TIMER_HEAD ): 72 bytes
Type 27 (FINALIZER_HEAD ): 18024 bytes
Type 31 (IO_PORT ): 144 bytes
Type 34 (APPDOMAIN_HEAD ): 72 bytes
Type 36 (APPDOMAIN_ASSEMBLY ): 2256 bytes[/quote]
And timer stop working, but sockets are send without problem. Could this be related? Any idea?
Thanks!!!


#13

Please never reply to a thread with a different question. This will confuse all reader and confuse you/us at the end.


#14

Sorry, I wan’t sure if this issue was related. Anyway, I’ll open a new thread.