locked
How can I convert this piece of code for a TCP socket receive from WP 8 to Win 8? RRS feed

  • Question

  • Hi,

    I know I'm asking a lot but I've tried the samples and tutorials for windows 8 sockets but I'm not having any success while I'm completely new and I've been following some lynda tutorials on programming I can't see how I can get this working piece of Windows Phone 8 Code,

    response = "Operation Timeout";
    
                // We are receiving over an established socket connection
                if (_socket != null)
                {
                    
                        // Create SocketAsyncEventArgs context object
                        SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
                        socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
    
                        // Setup the buffer to receive the data
                        socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
    
                        // Inline event handler for the Completed event.
                        // Note: This even handler was implemented inline in order to make 
                        // this method self-contained.
                        socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
                        {
                            if (e.SocketError == SocketError.Success)
                            {
                                { // Retrieve the data from the buffer
                                    response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
                                    response = response.Trim('\0');
                                    response = response.Replace("�", string.Empty);
                                    if (response.Length >= 5)
                                    {
                                        response = response.Substring(5, response.Length - 5);
                                    };
    
    
                                };
                            }
                            else
                            {
                                response = e.SocketError.ToString();
                            }
                            _clientDone.Set();
    
                            //mainCS._testR.Text = response;
                        });
    
                        // Sets the state of the event to nonsignaled, causing threads to block
                        _clientDone.Reset();
    
                        // Make an asynchronous Receive request over the socket
    
                            _socket.ReceiveAsync(socketEventArg);
    
                      /*  if (socketEventArg.BytesTransferred < 1)
                        {
                            Receive();
                        }; */
    
                        // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
                        // If no response comes back within this time then proceed
                        _clientDone.WaitOne(TIMEOUT_MILLISECONDS);
                    }
                else
                {
                    response = "Socket is not initialized";
                }
                return response;
            }

    to a version that works with Windows 8...
    I Tried to modify http://msdn.microsoft.com/en-us/library/windows/apps/jj150599.aspx to work but either got the text box to show one character and or nothing at all and I think its because I'm not waiting for the await reader.loadAsync to complete but that's it I have no idea how to code that! From what I understand in the above WP code the 

    socketEventArg

    is telling me the bytes were received so now parse it and give me the results (I've just deducted that as i'm trying to make sense of any of my code :( ) but I cannot for the life of me see any type of code samples that would offer a similar example thus expediting my learning and or app development.

    Could anyone either point me to a code sample or show a code sample to achieve what I'm achieving in WP 8 but for Windows 8 and explain to me in laymans terms what's going on?

    Regards,

    Adam


    -- djSupport

    Wednesday, January 29, 2014 1:09 AM

All replies

  • Have you seen the 8.1 samples?
    http://code.msdn.microsoft.com/windowsapps/site/search?query=socket&f%5B0%5D.Value=socket&f%5B0%5D.Type=SearchText&ac=4


    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    • Marked as answer by djSupport Wednesday, January 29, 2014 9:00 PM
    • Unmarked as answer by djSupport Wednesday, January 29, 2014 9:00 PM
    Wednesday, January 29, 2014 8:33 PM
    Moderator
  • There is not enough information about your server or this implementation to 'convert it' but there is a StreamSocket sample that is really good: http://code.msdn.microsoft.com/windowsapps/StreamSocket-Sample-8c573931

    If you understand that, then you can take the server portion and move that to phone.

    You should be able to bring up what you have already in the debugger and see what is happening as well and perhaps have some more questions.


    Jeff Sanders (MSFT)

    @jsandersrocks - Windows Store Developer Solutions @WSDevSol
    Getting Started With Windows Azure Mobile Services development? Click here
    Getting Started With Windows Phone or Store app development? Click here
    My Team Blog: Windows Store & Phone Developer Solutions
    My Blog: Http Client Protocol Issues (and other fun stuff I support)

    Wednesday, January 29, 2014 8:33 PM
    Moderator
  • I have tried to make sense of all samples but still haven't cracked it in particular the sockets sample

    -- djSupport

    Wednesday, January 29, 2014 8:42 PM
  • I do not know how the software I'm connecting to works i just understand that if I send an 8 or 9 byte code for example "FSBC00100" it fires back a list of captions from buttons within the software, typical "(Something uninteligable)button1,button2,button3" upto 26 then i split that into an array and populate button texts...

    -- djSupport

    Wednesday, January 29, 2014 8:47 PM
  • Hey DJ,

    I am not aware of a sample that does specifically what you want to do, but sockets are pretty easy to understand once you get the knack of it.  Maybe someone else will have done this and have a simple sample for you.  In the mean time, look at that sample I sent you and trace though it in the debugger.  That will allow you to see how it should work when everything is cool.  Then you can compare the results you see in the debugger when you run your attempt.

    Jeff


    Jeff Sanders (MSFT)

    @jsandersrocks - Windows Store Developer Solutions @WSDevSol
    Getting Started With Windows Azure Mobile Services development? Click here
    Getting Started With Windows Phone or Store app development? Click here
    My Team Blog: Windows Store & Phone Developer Solutions
    My Blog: Http Client Protocol Issues (and other fun stuff I support)

    Wednesday, January 29, 2014 8:48 PM
    Moderator
  • PS You can also request a sample from the Samples page as well.

    BTW.  What precisely are you trying to do with the sockets?  Are you an experienced Socket programmer?  This is low level stuff.


    Jeff Sanders (MSFT)

    @jsandersrocks - Windows Store Developer Solutions @WSDevSol
    Getting Started With Windows Azure Mobile Services development? Click here
    Getting Started With Windows Phone or Store app development? Click here
    My Team Blog: Windows Store & Phone Developer Solutions
    My Blog: Http Client Protocol Issues (and other fun stuff I support)


    Wednesday, January 29, 2014 8:49 PM
    Moderator
  • I also understood it from this example but in not sure I'm correct that if i created a listener on the local port it would respond according to the message recive but i was thrown off by the service name or number and couldn't get it to work, I'll re-look into and see how it goes it confuses me even more when the samples got all this fancy stuff in to show the example, which makes it a little harder for me to isolate the code making it all work (i wouldn't class my self as having overtly bad learning difficulties but in aware i have some so I have to take alot of q&a in my learning)

    -- djSupport

    Wednesday, January 29, 2014 8:52 PM
  • Just to confirm i have a wp app that comunicates with the windows software its rather like a remote control and it works fine in just trying to convert this to a windows 8 app so you can use a win 8 hybrid/tablet to connect to your base pc holding the software on a local network...

    -- djSupport

    Wednesday, January 29, 2014 8:56 PM
  • I'm on my phone at the moment working as a retail security guard ill try this all out when I'm home

    -- djSupport

    Wednesday, January 29, 2014 9:02 PM
  • Ah OK that helps... So your server (Windows Software) is a fixed format and you simply want to communicate with that. 

    Again, tracing through the Phone app in the debugger will help you immensely.  See what the happy path is, then compare to what you have so far.  Note the pattern, OpenSocket, establish comms, read bytes, close socket (respond whatever).  It sounds like you are close!


    Jeff Sanders (MSFT)

    @jsandersrocks - Windows Store Developer Solutions @WSDevSol
    Getting Started With Windows Azure Mobile Services development? Click here
    Getting Started With Windows Phone or Store app development? Click here
    My Team Blog: Windows Store & Phone Developer Solutions
    My Blog: Http Client Protocol Issues (and other fun stuff I support)

    Wednesday, January 29, 2014 9:04 PM
    Moderator
  • Its windows software for controlling nightclub disco lights my app simply sends it commands to activate buttons within the app we just have a list of codes we can send it ten of these 100 or so codes return information for example custom button labels so the app buttons reflect the buttons in the software the benefits of this are you could control the clubs/theatre lights as you move around but its terminology that throws me off and not having anyone to explain it to me then for example explain deeper if i didn't get parts of the conversation... So i can sort of understand the very basics lik

    e machine a is talking to machine b and b interprets what a is saying then provides a response but how does it handle that and what terminology is it does that make sense?


    -- djSupport

    Wednesday, January 29, 2014 9:15 PM
  • It seems like it would be easier to write a webservice that communicates directly with the app, then just communicate with the webservice so that you don't have to do socket programming.

    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Thursday, January 30, 2014 1:22 PM
    Moderator
  • Thats wayyyyyyyy beyond my knowledge and its designed mainly to use over a local network plus all I'm asking is the windows phone code above works fine but I cannot find an example that works in the same way for windows 8/rt

    -- djSupport

    Thursday, January 30, 2014 4:58 PM