StreamSocket.InputStream.AsStreamForRead() vs new DataReader(streamSocket.InputStream)/LoadAsync()

I'm using a StreamSocket in my WP8.1 (xaml) app and when reading data it sometimes returns 0.
my code looks like this:
var stream = _streamSocket.InputStream.AsStreamForRead(BufferSize);
var buffer = new byte[BufferSize];
while (true)
var readCount = await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
if (readCount <= 0)
throw new InvalidOperationException("No data to read in socket stream"); <---- error happens here
// process data and stop when marker in data is reached
my app sends a request to an http like server then expects to receive a response in the code above.
my question is: why does this happen ?
I recently switch from DataReader to standard .Net streams (using AsStreamForRead) and before the switch I wasn't getting this kind of error.
code before looked like this:
using (var dataReader = new DataReader(socket.InputStream))
dataReader.InputStreamOptions = InputStreamOptions.Partial;
await dataReader.LoadAsync(BufferSize).AsTask().ConfigureAwait(false);
// read as much as dataReader.UnconsumedBufferLength bytes....
dataReader.DetachStream();
can it happen that Stream.ReadAsync() doesn't wait for data to come in the socket
while DataReader/LoadAsync() does ?

Hi cuneyiit,
by "stream is over" you mean the streamsocket is closed ?
-> The stream is over means there is no more data coming and we can treat it as closed.
is it possible to see the source code of DataReader ? I know it's native code but since you are at microsoft can you perhaps look at what
DataReader.LoadAsync() does and how it does it using InputStream ?
-> Sorry I don't think its possible. It's not open source yet :P
--James
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey.

Similar Messages

  • My new ipad mini does not do anything

    I have a new ipad mini that does nothing. Tried reseting still nothing. Any ideas?

    Check what is set for Mail in Settings > Notifications. Badges must be allowed.
    Also check how often Mail is checking for new mail. See Settings > Mail, Contacts, Calendars > Fetch New Data

  • How do I/Can I define the interval Mail checks for new email?

    How do I/Can I define the interval Mail checks for new email?
    Thanks
    Glyaflya
    iPad 16G/3G ios 4.2.1

    Settings > Mail, Contacts, Calendars > Fetch New Data

  • A2DP API for bluetooth?

    Hi,
    I want to send a sound to a a BT module. This module is like a headset.
    I searched everywhere for a BT example for WP8 but I can't find any help.
    I have this code:
    StreamSocket socket = new StreamSocket();
    await socket.ConnectAsync(peer.HostName, "1");
    Why "1"? In the sample, RFCOMM is selected. If I want A2DP, what should I write?
    Another question is: is there an API for A2DP? The protocol is really hard to understand. And I don't know where to begin if I have to write all without any library... All with socket.OutputStream()?
    Hope someone can help me with this problem.
    Thank you!
    Adriano

    Thank you very much Mark,
    I was afraid, that it was not possible.
    WP8 has the A2DP and  AVRCP protocol, but developers have to write again the entire protocol that is already present in the system to communicate with BT speakers?
    I want to send 2 audio streams to 2 BT-speakers at the same time. Do you think, is it possible with Windows Phone 8?
    From your links, I saw that there is a way to send data to the device without RFCOMM.
    Old code:
    StreamSocket socket = new StreamSocket();
    await socket.ConnectAsync(peer.HostName, "1");
    New code:
    StreamSocket socket = new StreamSocket();
    await socket.ConnectAsync(peer.HostName, "{0000110D-0000-1000-8000-00805F9B34FB}");
    DataWriter dataWriter = new DataWriter(socket.OutputStream);
    DataReader dataReader = new DataReader(socket.InputStream);
    AdvancedAudioDistributionService: GUID = {0000110D-0000-1000-8000-00805F9B34FB}
    AudioSourceService: GUID = {0000110A-0000-1000-8000-00805F9B34FB}
    HeadsetService: GUID = {00001108-0000-1000-8000-00805F9B34FB}
    I will try with this.
    Thank you again for the links. Once I got it, I will insert a little example on this topic. Maybe it can help someone.
    Adriano

  • Qosmio F50-10M: how to deactivate touchpad?

    Hello guys,
    usually I use a USB driven mouse to operate Win7. While writing text I often get in contact with the touch pad unwanted.
    As I cannot identify the appropriate device within the hardware manager I am not able to deactive the touchpad while using the mouse.
    There a lot of HID (Human Interface Devices) without a unique identifier.
    How can I deactivate the touch pad or is there a way of deactivating automatically while plugging the USB mouse?
    Thank you for your help!
    Yours,
    Starmind

    Dear Xardas,
    thank your for your answer.
    Unfortunately, there is no Synaptics driver shown in control panel which could be removed. How can I do this?
    The only driver recognized by the system seems to be the Alps Electric driver.
    Did you test using the VAP from the Satellite L500 on a Qosmio F50? Checking downloads on that model there pops up a lot of different types (of that model), for example L500-ST2521, L500-ST2522 and so forth. What version could work proper for my Qosmio F50-10M?
    Checking possible downloads for TVAP and Windows7 64bit there are six different downloads offered. For instance there two different download links for version v1.2.27_64 same size of file named "Toshiba Value Added Package for Windows 7/Vista (64).
    Then there is
    "Toshiba Value Added Package for Windows 7 (64) v1.2.26_64;10-07-2009"
    Which are the differences of those files?
    Couldnt I install one of those files? If so what file should I choose?
    Your help and your answer is highly appreciated.
    Yours,
    Starmind_1
    Message was edited by: Starmind_1 because of new data

  • My iPhone won't recognize that my friend changed her iPhone number...

    My friend changed her iPhone number.  When I iMessage her, it keeps saying her messages are from and going to her old number.  Can I update this? I have added her new number and try to use it.

    You have deleted the old record
    if you updated it try deleting and recreating with new data

  • Form on screen, not updating for new data on inputstream

    I'm writing a j2me midlet that will initiate a bluetooth connection to another device. I have been able to set up the inputstreams and outputstreams and send some data between the two devices using serial port emulation.
    The following is the code for this part of the program:
    ServiceRecord s = (ServiceRecord) serviceVector.elementAt(a);
            int data[] = new int[10000];
            InputStream in = null;
            OutputStream out = null;
            Form dataForm = new Form("Data");
            dataForm.addCommand(exitCommand);
            dataForm.addCommand(backCommand);
            dataForm.setCommandListener(this);
            display.setCurrent(dataForm);
            try {
                StreamConnection conn = null;
                String url = null;
                try {
                    url = s.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                    conn = (StreamConnection) Connector.open(url);
                } catch (IOException e) {
                    System.err.println("Note: can't connect to: " + url);
                in = conn.openDataInputStream();
                out = conn.openDataOutputStream();
                int ch;
                out.flush();
                    while (((ch) = in.read()) != -1) {
                        String aChar = new Character((char)ch).toString();
                        dataForm.append(aChar);
                        dataForm.append("\n");
                conn.close();My problem is that the midlet on the mobile phone will only update its window to display the new screen as a form once the connection has been terminated, that is when the while loop has been broken. Is there a way in which to display the form while the inputstream is waiting for data and then watch the addition of data in real time to the form?
    I am relatively new to java and have searched the forum/ internet for such a problem but have not been able to find a solution. Cheers

    I don't think that is it now that we are into Monday and it still hasn't updated. Anybody else having issues with their text descriptino not updating? What's a good email address to contact apple about the problem. Non of the "contact Us" email addresses seem to fit the description. The [email protected] is a blackhole.

  • How can I convert an InputStream to a FileInputStream ???

    How can I convert an InputStream to a FileInputStream ???

    Thanks for you reply, however, I am still stuck.
    I am trying to convert my application (which runs smoothly) to a signed applet. The following is the original (application) code:
    private void loadConfig() {
    String fileName = "resources/groupconfig";
    File name = new File(fileName);
    if(name.isFile()) {
    try {
         ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
         pAndGConfig = (PAGroupsConfig)in.readObject();
         in.close();
         return;
    } catch(ClassNotFoundException e) {
         System.err.println("++ERROR: "+e);
    } catch(IOException e) {
         System.err.println("++ERROR: "+e);
    System.out.println("Can't find file: " + fileName);
    Because all code and resources now reside in a Jar file (for the signed applet), I must use the following line to access the resources:
    InputStream is = this.getClass().getResourceAsStream(fileName);
    I then need to convert the 'InputStream' to 'ObjectInputStream' or 'FileInputStream' so that I can work with it.
    I would be very grateful if you could help shed some light on the matter - Cobram

  • App running under lock screen with StreamSocket and SpeechSynthesizer

    On wp8 silverlight this was easy. PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
    In 8.1 xaml how would I go about this? I have found an ugly hack online that keeps the screen alive, this is not a solution that I can use. My users need to start my app, select a car transponder that they want to hear lap times from, connect to my server
    (over wifi to a local computer running my server code, no internet) hit the lock button, then put their phones in their pockets while they drive and get the lap times on their earpiece. 
    I have the new and more cumbersome text-to-speech working (how you have to have an invisible media element on a the active page for mediaended to fire was especially annoying!). I have the streamsocket stuff working, just not under the lock screen. I don't
    really need it to be a "background task". It is understood and preferable that it disconnects the moment you leave the page where get your live lap times. 
    controlchanneltrigger seemed promising, you can use it for store apps... but not phone.
    To summarize.
    1. connect to server with streamsocket api
    2. lock screen and put phone in pocket
    3. app should stay alive and as packets arrive from the server (one packet every 10 seconds on average), store lap time results and say them out loud using text to speech.
    https://youtu.be/0VnOh6s3hww
    At this point I'm pretty fed up and I'm about to pull the plug on the WP8.1 version, my first experience with xaml was... unpleasant... So if you have some good keywords I can search for that would be appreciated.

    Hi torg,
    The most similar API on Windows Phone 8.1 is
    RequestActive | requestActive method, see this for more information: How to keep the display on during audio/video playback (XAML)
    --James
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Reading from socket inputstream returns -1

    I'm using a socket in order to connect to a chat server. The code is:
    Socket socket;
    InputStreamReader isr;
    OutputStreamWriter osw;
    try {
      socket = new Socket(sHost, iPort);
      isr = new InputStreamReader(socket.getInputStream());
      osw = new OutputStreamWriter(socket.getOutputStream());
      int iCharRead;
      char[] buffer = new char[512];
      while((iCharRead=isr.read(buffer, 0, 512))!=-1) {
          // do something
      System.err.println("Error: InputStream has returned -1.");
      System.err.println("\tsocket.isBound()=" + socket.isBound());
      System.err.println("\tsocket.isClosed()=" + socket.isClosed());
      System.err.println("\tsocket.isConnected()=" + socket.isConnected());
      System.err.println("\tsocket.isInputShutdown()=" + socket.isInputShutdown());
      System.err.println("\tsocket.isOutputShutdown()=" + socket.isOutputShutdown());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {if (isr!=null) isr.close();} catch (Exception ex) {}
      try {if (osw!=null) osw.close();} catch (Exception ex) {}
      try {if (socket!=null) socket.close();} catch (Exception ex) {}
    }Ther server is supposed to be sending data continuously but sometimes, after being connected successfully for a while, the read method returns -1. As you can see in the previous code then I'm checking out some socket information and I get:
    Error: InputStream has returned -1.
         socket.isBound()=true
         socket.isClosed()=false
         socket.isConnected()=true
         socket.isInputShutdown()=false
         socket.isOutputShutdown()=falseThe socket seems to be bounded, it is not closed and isConnected also returns true. Besides, input and output streams are not closed. So, why does the read method return -1? What does it really mean? Is it a problem in the server side, that is overloaded or simply malfunctioning? What can I do in order to keep on reading data from the socket connection? Do I have to close the current socket and reconnect again to the server or is there any other way to recover from this situation?
    Thanks.

    isConnected means was ever connected.
    Check whether isr is closed. If so, the server has disconnected/closed the connection.

  • How to get all data from inputstream?

    I have written a program to download pages from web sites,
    but sometimes I can't get all the content of the page,
    How can I do?

    //Try the following code:
    //It works in all cases (as long as the client is not //hid beneath a or proxy).
    import java.net.*;
    import java.io.*;
    public class webClient {
         public static void main(String args[]) {
              try{
                   if(args.length < 1) {
                        System.out.println("webClient URL");
                        System.exit(0);
                   URL u = new URL(args[0]);
                   BufferedInputStream inputStream = new BufferedInputStream((u.openConnection()).getInputStream());
                   int n;
                   byte[] buff = new byte[2048];
                   ByteArrayOutputStream out = new ByteArrayOutputStream();
                   while((n = inputStream.read(buff)) >= 0)
                        out.write(buff, 0, n);
                   System.out.println(out.toString());
              } catch(Exception e) {
                   e.printStackTrace();
    }

  • Problem with Thread and InputStream

    Hi,
    I am having a problem with threads and InputStreams. I have a class which
    extends Thread. I have created and started four instances of this class. But
    only one instance finishes its' work. When I check the state of other three
    threads their state remains Runnable.
    What I want to do is to open four InputStreams which are running in four
    threads, which reads from the same url.
    This is what I have written in my thread class's run method,
    public void run()
         URL url = new URL("http://localhost/test/myFile.exe");
    URLConnection conn = url.openConnection();
    InputStream istream = conn.getInputStream();
    System.out.println("input stream taken");
    If I close the input stream at the end of the run method, then other threads
    also works fine. But I do not want to close it becuase I have to read data
    from it later.
    The file(myFile.exe) I am trying to read is about 35 MB in size.
    When I try to read a file which is about 10 KB all the threads work well.
    Plz teach me how to solve this problem.
    I am using JDK 1.5 and Win XP home edition.
    Thanks in advance,
    Chamal.

    I dunno if we should be doing such things as this code does, but it works fine for me. All threads get completed.
    public class ThreadURL implements Runnable
        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
        public void run()
            try
                URL url = new URL("http://localhost:7777/java/install/");
                URLConnection conn = url.openConnection();
                InputStream istream = conn.getInputStream();
                System.out.println("input stream taken by "+Thread.currentThread().getName());
                istream.close();
                System.out.println("input stream closed by "+Thread.currentThread().getName());
            catch (MalformedURLException e)
                System.out.println(e);
                //TODO Handle exception.
            catch (IOException e)
                System.out.println(e);
                //TODO Handle exception.
        public static void main(String[] args)
            ThreadURL u = new ThreadURL();
            Thread t = new Thread(u,"1");
            Thread t1 = new Thread(u,"2");
            Thread t2 = new Thread(u,"3");
            Thread t3 = new Thread(u,"4");
            t.start();
            t1.start();
            t2.start();
            t3.start();
    }And this is the o/p i got
    input stream taken by 2
    input stream closed by 2
    input stream taken by 4
    input stream closed by 4
    input stream taken by 3
    input stream closed by 3
    input stream taken by 1
    input stream closed by 1
    can u paste your whole code ?
    ram.

  • Problem with InputStream in a MIDlet

    I am doing some client/server networking using a socket connection in a MIDlet.
    When I make the socket connection I get a 220 reply.
    i.e "220 smtp.comcast.net"
    I read the status code from that response and then send the server my next command. (HELO). so far so good.
    The server returns a status code of 250. I can see that in my packet sniffer. again, this is a good thing.
    The problem is with my input stream. When I last read the input stream ch = is.read();
    the input stream didn't empty itself.
    So every time I get a response from the server, it appends to the last input I had.
    in this case:
    "220 smtp.comcast.net 250 comcast.net".
    I only expect to see:
    "250 comcast.net"
    I've tried is.close() and then reopening it when I expect a response from the server. This does not flush it.
    What can I do to rectify this?
    Thanks in advance,
    Mike

    or better, use a buffer to write to and give the number of read bytes to it:
    InputStream is; // from somewhere else in the MIDlet
    String rec;
    StringBuffer sb = new StringBuffer();
    byte[] buf = new byte[1024];
                   while( (c=is.read(buf)) != -1 ){
                        rec=new String(buf,0,c);
                        sb.append(rec);
                   };c is the number of bytes which were read from the input stream.
    so i save the read bytes into a new string, but only bytes 0-c from the bytearray buf.
    then, i append the whole string to a stringbuffer for later use.

  • How to create a MimeBodyPart properly with an InputStream in the constructo

    I am looping through a list of email attachments.
    In this loop I am doing the following:
    (Don't worry about the Core object, it works and returns a valid InputStream, tested this before by just reading out the bytes)
                     InputStream attachInputStream = Core.getFileDocumentContent(attachObject);
                       System.out.println("available for original stream: " + attachInputStream.available());
                       MimeBodyPart attachmentBodyPart = new MimeBodyPart(attachInputStream);
                       InputStream testStream = attachmentBodyPart.getInputStream();
                       System.out.println("available for retrieved stream: " + testStream.available());
                       attachmentBodyPart.setFileName(attachment.getName());
                   multipart.addBodyPart(attachmentBodyPart);Because my received attachments were always empty, I added a few println's to check where this were going wrong. Following is the output when I run the application:
    available for original stream: 119
    available for retrieved stream: 0
    So, apparently something goes wrong in the constructor for MimeBodyPart.
    I hope I'm just doing something silly but I'm out of options at the moment apart of writing a lot of extra code to handle converting an InputStream to a MimeBodypart myself.
    Anyone with some ideas?
    edit: I just read I cannot use available after getting an inputstream from a mimebodypart. So I'll go and make another check. Problem still exists though, I'm not getting an attachment after mailing it.
    Edited by: Bas_Rotterdam on Apr 15, 2009 3:16 AM

    I'm not clear on what you're trying to accomplish.
    Are you trying to create a message with attachments, where the content of the
    attachments comes from InputStreams from your Core object? If so, you're
    going about it the wrong way.
    The MimeBodyPart constructor expects the input stream to be formatted as
    an entire body part - headers plus content. You only have the content. For
    that you want to use the setContent method or one of the related methods
    (setDataHandler, setText, attachFile) that sets the content of the body part.
    See the sendfile.java demo program included with JavaMail for an example of
    creating an attachment with content from a file.
    And don't forget to read the [JavaMail FAQ|http://java.sun.com/products/javamail/FAQ.html].

  • InputStream / OutputStream Help

    I have in a series 10 commands to be executed on a server. so i am using Buffered OutputStream and DataOutputStream to write those commands to server.
    these commands have a set of protocol rule to be followed.
    for example i am creating a byte array and i am appending those protocol rules to the byte array and then finally to the stream and then writing to the socket of the server.
    everything works fine here.
    After that i must read the messages from the server.
    this is also fine but t�he problem is everytime i read different input for each command.
    i dont know why!!!!
    so my read function is as follows,
    import java.net.*;
    public class xxxxx
    InputStream instream;
    OutputStream outstream;
    public void OpenConnection() throws ConnectException,UnknownHostException
    try
         tcpipSocket = new Socket(tcpipparameters.getIpAddress(),tcpipparameters.getPortNumber());
    catch(IOException exception)
         System.out.println(exception.toString());
    try
         outstream = tcpipSocket.getOutputStream();
         instream = tcpipSocket.getInputStream();
         dos = new DataOutputStream(outstream);
         BufferedOutputStream bos= new BufferedOutputStream(dos);
         dis = new DataInputStream(instream);
         BufferedInputStream bis = new BufferedInputStream(dis);
    ////////// now i start the command execution on the server
    ///// The 1st Command --------------(The INIT Command)
         byte[] init = {0,6,0,2};
         init = createMessage.calculateCheckSum(init);
         int len = init.length;
         //dos.write(init,0,len);
         bos.write(init);
         bos.flush();
         int available;
         while((available = bis.available()) > 0)
              byte[] data = new byte[available];
              bis.read(data);
              for(int i = 0 ; i < data.length; i++)
                   System.out.print(data);
    ////////////////// The 2nd Command -------------------(IDENTIFY)
    byte[] identify = {0,16,0,20};
    // The protocol version number is inserted in to the IDENTIFY byte[]array
    int protocol_version_number = 512;
    byte[] protocol = {(byte)(protocol_version_number/256) ,(byte)(protocol_version_number%256) };
    byte[] temp = new byte[ identify.length +  protocol.length] ;
    System.arraycopy( identify, 0, temp, 0, identify.length ) ;
    System.arraycopy(protocol, 0, temp, identify.length, protocol.length ) ;
    identify = temp ;
    String PR_SName = "PRS2.0";
    identify = createString.stringData(identify,PR_SName);
    identify = createMessage.calculateCheckSum(identify);
    len = identify.length;
    bos.write(identify);
    bos.flush();
    int length1 = bis.available();
    System.out.println("length of the BufferedInputStream = " + length1);
    StringBuffer sb = new StringBuffer();
    for (int i=1; i<=length1; i++)
         char reply = (char)bis.read();
         sb.append(reply);
    System.out.println(sb.toString());
    ////////////////// The 3rd Command and So on................................
    catch(IOException exception)
         System.err.println("message = " + exception.getMessage());
    catch(InterruptedException e)
         System.err.println("Error =" + e);
    finally
         try
              //flush and close both "Instream" and "Outstream"
              dos.close();
              dis.close();
              instream.close();
              outstream.close();
         catch (IOException ex)
              ex.printStackTrace();
    every time the reading from the server is different.
    but i want to have the exact number of bytes to read everytime.
    so please correct me where i am wrong.
    With regards,
    Ashok
              public void CloseConnection()throws IOException
                        tcpipSocket.close();

    I would say the answer is in my previous replies to your question. I suggest you have another read of them.

Maybe you are looking for