StreamReader not reading all lines

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • JoKur

    StreamReader not reading all lines

    Hello,

    First let me tell you that I'm very new to C# and learning as I go. I'm
    trying to write a client application to communicate with a server (that I
    didn't write). Each message from the server is on one line (\r\n at end) and
    is formed as [Message] [Optional Argument1] [Optional Argument2] - each of
    which is seperated by a space. Arguments with spaces in them are enclosed in
    quotations.

    So, I'm able to open a connection to the server. When I send a message to
    it, it immediately responds and I parse that using a streaReader.Rea dline().
    - That part works. The problem is that the server is also sending status
    messages every couple of seconds which seem to get lost. I didn't know how
    to have it raise an event when data is present at the stream, so I setup a
    timer to poll the stream.

    I've tried using "streamReader.P eek() != null" but it hangs, I've tried just
    streamReader.Re adLine() but it hangs. Any suggestions are greatly
    appreciated. I'm using Beta 2

    Code is below

    Thanks in advance!!
    Joe


    using System;
    using System.Componen tModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows. Forms;
    using System.Collecti ons;
    using System.Threadin g;
    using System.Net.Sock ets;
    using System.IO;

    public delegate void ConnectionHandl er(bool State);
    public delegate void ControlChangeHa ndler(String Message);

    public partial class MMConnection : Form
    {

    //--------------------------------------------------------------
    // Class Variables
    private NetworkStream netStream;
    private StreamWriter netWriter;
    private StreamReader netReader;
    public TcpClient netClient;
    private bool netClientStart = false;
    private bool netClientConnec ted = false;

    private System.Net.IPAd dress ipAddress =
    System.Net.IPAd dress.Parse("12 7.0.0.1");
    private int ipPort = 1632;
    private String strUsername = "Contempora ry";
    private String strPassword = "techspa";
    private bool blnLoggedIn = false;

    // Define events this class can raise
    public event ConnectionHandl er OnConnectionCha nged;
    public event ControlChangeHa ndler OnControlChange d;

    //--------------------------------------------------------------
    // Constructor
    public MMConnection()
    {
    InitializeCompo nent();
    }

    // Startup the client
    public void ConnectionStart ()
    {
    netClientStart = true;
    tmrStatus.Enabl ed = true;
    }

    public void ConnectionStop ()
    {
    try
    {
    logToScreen("Cl osing connection");

    // Close connection
    netWriter.Close ();
    netReader.Close ();
    netStream.Close ();
    netClient.Close ();
    }
    catch (Exception e)
    {
    logToScreen("Er ror closing connection: " + e.Message.ToStr ing());
    }
    }

    private void StreamWrite (string strMessage)
    {
    try
    {
    if (strMessage != "sg") logToScreen("Se nding string: " + strMessage);
    netWriter.Write (strMessage + "\r\n");
    netWriter.Flush ();
    }
    catch (Exception e)
    {
    netClientConnec ted = false; // Cannot send - client must have disconnected
    Console.WriteLi ne("Error sending string: " + e.Message.ToStr ing());
    }
    }

    public void MessageSend(str ing strMessage)
    {
    StreamWrite(str Message);
    }

    // Send Password to the server
    private void sendLogin()
    {
    StreamWrite("li " + " " + strUsername + " " + strPassword);
    }

    // Parse responses from the server
    private void ProcessString(S tring strData)
    {
    int foundPosition; //Position of the first space
    String firstToken; //The first token (command or error

    // Parse out the first token
    foundPosition = strData.IndexOf (@" ");
    if (foundPosition > -1)
    {
    firstToken = strData.Substri ng(0, foundPosition). ToString();
    }
    else
    {
    firstToken = strData.ToStrin g();
    }

    // Act on the first token
    switch (firstToken)
    {
    case "notLoggedI n":
    sendLogin();
    break;

    case "loggedIn":
    blnLoggedIn = true;
    logToScreen("Lo gged into MediaMatrix");
    UpdateConnectio nIndicator(netC lient.Connected );
    break;

    case "statusIs":
    blnLoggedIn = true;
    break;

    case "valueIs":
    OnControlChange d(strData);
    break;

    default: //no token
    break;
    }
    }

    private void tmrStatus_Tick( object sender, EventArgs e)
    {
    if (netClientConne cted)
    {
    tmrRead.Enabled = true;
    StreamWrite("sg "); //Status Get
    }
    else
    {
    if (netClientStart )
    {
    try
    {

    netClient = new TcpClient();
    // Create TcpClient and connect to server
    netClient.Conne ct(ipAddress, ipPort);
    //UpdateConnectio nIndicator(netC lient.Connected ); //Moved to after
    login

    // Get network Stream associated with TcpClient
    netStream = netClient.GetSt ream();
    netClientConnec ted = true;
    logToScreen("Co nnection Successfull to: " + ipAddress + " port: " +
    ipPort);

    // Create readers and writers
    netReader = new StreamReader(ne tStream);
    netWriter = new StreamWriter(ne tStream);
    Console.WriteLi ne("Got Streams!");
    }
    catch (Exception error)
    {
    Console.Write ("Error: " + error.ToString( ));
    netClientConnec ted = false;
    }
    }
    }

    // Update the color
    //UpdateConnectio nIndicator(netC lient.Connected );
    }

    private void logToScreen(Str ing strMessage)
    {
    lstReceive.Item s.Add(strMessag e);
    Console.WriteLi ne(strMessage);
    }

    private void btnSend_Click(o bject sender, EventArgs e)
    {
    StreamWrite(txt Send.Text);
    }

    private void tmrRead_Tick(ob ject sender, EventArgs e)
    {
    String strData;

    try
    {
    // Read and display lines from the network stream
    //while(netStream .DataAvailable)
    // logToScreen("En d of Stream: " + netReader.EndOf Stream);
    // logToScreen("Ne t Reader: " + netReader.ReadL ine().ToString( ));
    // logToScreen("En d of Stream: " + netReader.EndOf Stream);
    while (netStream.Data Available)
    {
    try
    {
    // Grab data from socket
    strData = netReader.ReadL ine();

    // Clean it up a bit
    strData = strData.Trim(ne w char[3] { '\a', '\r', '\n' });

    // Send it on to be parsed
    logToScreen("Re ceived string: " + strData);
    ProcessString(s trData);
    }
    catch (Exception ex)
    {
    logToScreen("Er ror reading string: " + ex.Message.ToSt ring());
    }
    }
    }
    catch (Exception exc)
    {
    logToScreen("Er ror Receiving: " + exc.Message.ToS tring());
    }
    }

    public static string[] Tokenize(string strIncoming)
    {
    //TODO: Put regular expresstion
    System.Text.Reg ularExpressions .Regex regFilter = new
    System.Text.Reg ularExpressions .Regex
    ( @"\a|\s" );

    return (regFilter.Spli t(strIncoming)) ;
    }

    private void UpdateConnectio nIndicator(bool blnConnected)
    {
    if (blnConnected)
    {
    staStripConnect ed.Text = "Connected" ;
    staStripConnect ed.BackColor = System.Drawing. Color.LightGree n;
    }
    else
    {
    staStripConnect ed.Text = "Not Connected";
    staStripConnect ed.BackColor = System.Drawing. Color.Red;
    }

    //Raise Event to calling form
    OnConnectionCha nged(blnConnect ed);
    }

    }// MMConnection end
  • Nicholas Paldino [.NET/C# MVP]

    #2
    Re: StreamReader not reading all lines

    JoKur,

    What I would do is have the StreamReader run in a loop, reading lines as
    they come (it will hang in between). The key though is to have the
    StreamReader run on another thread, which would raise an event when the
    message is received. This way, you won't have to worry about hanging your
    application, and can get notifications when the messages come in.

    Hope this helps.


    --
    - Nicholas Paldino [.NET/C# MVP]
    - mvp@spam.guard. caspershouse.co m

    "JoKur" <Joe@JoKur.ne t> wrote in message
    news:58910318-A143-474F-BC00-EB0CE2390597@mi crosoft.com...[color=blue]
    > Hello,
    >
    > First let me tell you that I'm very new to C# and learning as I go. I'm
    > trying to write a client application to communicate with a server (that I
    > didn't write). Each message from the server is on one line (\r\n at end)
    > and
    > is formed as [Message] [Optional Argument1] [Optional Argument2] - each of
    > which is seperated by a space. Arguments with spaces in them are enclosed
    > in
    > quotations.
    >
    > So, I'm able to open a connection to the server. When I send a message to
    > it, it immediately responds and I parse that using a
    > streaReader.Rea dline().
    > - That part works. The problem is that the server is also sending status
    > messages every couple of seconds which seem to get lost. I didn't know
    > how
    > to have it raise an event when data is present at the stream, so I setup a
    > timer to poll the stream.
    >
    > I've tried using "streamReader.P eek() != null" but it hangs, I've tried
    > just
    > streamReader.Re adLine() but it hangs. Any suggestions are greatly
    > appreciated. I'm using Beta 2
    >
    > Code is below
    >
    > Thanks in advance!!
    > Joe
    >
    >
    > using System;
    > using System.Componen tModel;
    > using System.Data;
    > using System.Drawing;
    > using System.Text;
    > using System.Windows. Forms;
    > using System.Collecti ons;
    > using System.Threadin g;
    > using System.Net.Sock ets;
    > using System.IO;
    >
    > public delegate void ConnectionHandl er(bool State);
    > public delegate void ControlChangeHa ndler(String Message);
    >
    > public partial class MMConnection : Form
    > {
    >
    > //--------------------------------------------------------------
    > // Class Variables
    > private NetworkStream netStream;
    > private StreamWriter netWriter;
    > private StreamReader netReader;
    > public TcpClient netClient;
    > private bool netClientStart = false;
    > private bool netClientConnec ted = false;
    >
    > private System.Net.IPAd dress ipAddress =
    > System.Net.IPAd dress.Parse("12 7.0.0.1");
    > private int ipPort = 1632;
    > private String strUsername = "Contempora ry";
    > private String strPassword = "techspa";
    > private bool blnLoggedIn = false;
    >
    > // Define events this class can raise
    > public event ConnectionHandl er OnConnectionCha nged;
    > public event ControlChangeHa ndler OnControlChange d;
    >
    > //--------------------------------------------------------------
    > // Constructor
    > public MMConnection()
    > {
    > InitializeCompo nent();
    > }
    >
    > // Startup the client
    > public void ConnectionStart ()
    > {
    > netClientStart = true;
    > tmrStatus.Enabl ed = true;
    > }
    >
    > public void ConnectionStop ()
    > {
    > try
    > {
    > logToScreen("Cl osing connection");
    >
    > // Close connection
    > netWriter.Close ();
    > netReader.Close ();
    > netStream.Close ();
    > netClient.Close ();
    > }
    > catch (Exception e)
    > {
    > logToScreen("Er ror closing connection: " + e.Message.ToStr ing());
    > }
    > }
    >
    > private void StreamWrite (string strMessage)
    > {
    > try
    > {
    > if (strMessage != "sg") logToScreen("Se nding string: " + strMessage);
    > netWriter.Write (strMessage + "\r\n");
    > netWriter.Flush ();
    > }
    > catch (Exception e)
    > {
    > netClientConnec ted = false; // Cannot send - client must have disconnected
    > Console.WriteLi ne("Error sending string: " + e.Message.ToStr ing());
    > }
    > }
    >
    > public void MessageSend(str ing strMessage)
    > {
    > StreamWrite(str Message);
    > }
    >
    > // Send Password to the server
    > private void sendLogin()
    > {
    > StreamWrite("li " + " " + strUsername + " " + strPassword);
    > }
    >
    > // Parse responses from the server
    > private void ProcessString(S tring strData)
    > {
    > int foundPosition; //Position of the first space
    > String firstToken; //The first token (command or error
    >
    > // Parse out the first token
    > foundPosition = strData.IndexOf (@" ");
    > if (foundPosition > -1)
    > {
    > firstToken = strData.Substri ng(0, foundPosition). ToString();
    > }
    > else
    > {
    > firstToken = strData.ToStrin g();
    > }
    >
    > // Act on the first token
    > switch (firstToken)
    > {
    > case "notLoggedI n":
    > sendLogin();
    > break;
    >
    > case "loggedIn":
    > blnLoggedIn = true;
    > logToScreen("Lo gged into MediaMatrix");
    > UpdateConnectio nIndicator(netC lient.Connected );
    > break;
    >
    > case "statusIs":
    > blnLoggedIn = true;
    > break;
    >
    > case "valueIs":
    > OnControlChange d(strData);
    > break;
    >
    > default: //no token
    > break;
    > }
    > }
    >
    > private void tmrStatus_Tick( object sender, EventArgs e)
    > {
    > if (netClientConne cted)
    > {
    > tmrRead.Enabled = true;
    > StreamWrite("sg "); //Status Get
    > }
    > else
    > {
    > if (netClientStart )
    > {
    > try
    > {
    >
    > netClient = new TcpClient();
    > // Create TcpClient and connect to server
    > netClient.Conne ct(ipAddress, ipPort);
    > //UpdateConnectio nIndicator(netC lient.Connected ); //Moved to after
    > login
    >
    > // Get network Stream associated with TcpClient
    > netStream = netClient.GetSt ream();
    > netClientConnec ted = true;
    > logToScreen("Co nnection Successfull to: " + ipAddress + " port: " +
    > ipPort);
    >
    > // Create readers and writers
    > netReader = new StreamReader(ne tStream);
    > netWriter = new StreamWriter(ne tStream);
    > Console.WriteLi ne("Got Streams!");
    > }
    > catch (Exception error)
    > {
    > Console.Write ("Error: " + error.ToString( ));
    > netClientConnec ted = false;
    > }
    > }
    > }
    >
    > // Update the color
    > //UpdateConnectio nIndicator(netC lient.Connected );
    > }
    >
    > private void logToScreen(Str ing strMessage)
    > {
    > lstReceive.Item s.Add(strMessag e);
    > Console.WriteLi ne(strMessage);
    > }
    >
    > private void btnSend_Click(o bject sender, EventArgs e)
    > {
    > StreamWrite(txt Send.Text);
    > }
    >
    > private void tmrRead_Tick(ob ject sender, EventArgs e)
    > {
    > String strData;
    >
    > try
    > {
    > // Read and display lines from the network stream
    > //while(netStream .DataAvailable)
    > // logToScreen("En d of Stream: " + netReader.EndOf Stream);
    > // logToScreen("Ne t Reader: " + netReader.ReadL ine().ToString( ));
    > // logToScreen("En d of Stream: " + netReader.EndOf Stream);
    > while (netStream.Data Available)
    > {
    > try
    > {
    > // Grab data from socket
    > strData = netReader.ReadL ine();
    >
    > // Clean it up a bit
    > strData = strData.Trim(ne w char[3] { '\a', '\r', '\n' });
    >
    > // Send it on to be parsed
    > logToScreen("Re ceived string: " + strData);
    > ProcessString(s trData);
    > }
    > catch (Exception ex)
    > {
    > logToScreen("Er ror reading string: " + ex.Message.ToSt ring());
    > }
    > }
    > }
    > catch (Exception exc)
    > {
    > logToScreen("Er ror Receiving: " + exc.Message.ToS tring());
    > }
    > }
    >
    > public static string[] Tokenize(string strIncoming)
    > {
    > //TODO: Put regular expresstion
    > System.Text.Reg ularExpressions .Regex regFilter = new
    > System.Text.Reg ularExpressions .Regex
    > ( @"\a|\s" );
    >
    > return (regFilter.Spli t(strIncoming)) ;
    > }
    >
    > private void UpdateConnectio nIndicator(bool blnConnected)
    > {
    > if (blnConnected)
    > {
    > staStripConnect ed.Text = "Connected" ;
    > staStripConnect ed.BackColor = System.Drawing. Color.LightGree n;
    > }
    > else
    > {
    > staStripConnect ed.Text = "Not Connected";
    > staStripConnect ed.BackColor = System.Drawing. Color.Red;
    > }
    >
    > //Raise Event to calling form
    > OnConnectionCha nged(blnConnect ed);
    > }
    >
    > }// MMConnection end[/color]


    Comment

    • Jon Skeet [C# MVP]

      #3
      Re: StreamReader not reading all lines

      JoKur <Joe@JoKur.ne t> wrote:[color=blue]
      > First let me tell you that I'm very new to C# and learning as I go. I'm
      > trying to write a client application to communicate with a server (that I
      > didn't write). Each message from the server is on one line (\r\n at end) and
      > is formed as [Message] [Optional Argument1] [Optional Argument2] - each of
      > which is seperated by a space. Arguments with spaces in them are enclosed in
      > quotations.
      >
      > So, I'm able to open a connection to the server. When I send a message to
      > it, it immediately responds and I parse that using a streaReader.Rea dline().
      > - That part works. The problem is that the server is also sending status
      > messages every couple of seconds which seem to get lost. I didn't know how
      > to have it raise an event when data is present at the stream, so I setup a
      > timer to poll the stream.
      >
      > I've tried using "streamReader.P eek() != null" but it hangs, I've tried just
      > streamReader.Re adLine() but it hangs. Any suggestions are greatly
      > appreciated. I'm using Beta 2[/color]

      Does the server flush the stream after sending the status code? It
      sounds like it isn't, or that it's not sending a line terminator after
      the status code.

      Have you tried using a network sniffer to check that the information is
      coming over the wire?

      --
      Jon Skeet - <skeet@pobox.co m>
      Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

      If replying to the group, please do not mail me too

      Comment

      • JoKur

        #4
        Re: StreamReader not reading all lines

        Jon,

        It ends each line with \r\n, which is supposedly what ReadLine() looks for.
        I can see this when I connect using Telnet.

        I had another thought, is it possible that the server is sending more than
        one line but when I'm reading them, I'm only grabbing the first line?

        In other words... What happens if I'm accessing the stream (like writing to
        it), when something else comes in? Is there a way to ask how many lines it
        sees and then do a ReadLine() for each one?

        --
        Thanks
        Joe


        "Jon Skeet [C# MVP]" wrote:
        [color=blue]
        > JoKur <Joe@JoKur.ne t> wrote:[color=green]
        > > First let me tell you that I'm very new to C# and learning as I go. I'm
        > > trying to write a client application to communicate with a server (that I
        > > didn't write). Each message from the server is on one line (\r\n at end) and
        > > is formed as [Message] [Optional Argument1] [Optional Argument2] - each of
        > > which is seperated by a space. Arguments with spaces in them are enclosed in
        > > quotations.
        > >
        > > So, I'm able to open a connection to the server. When I send a message to
        > > it, it immediately responds and I parse that using a streaReader.Rea dline().
        > > - That part works. The problem is that the server is also sending status
        > > messages every couple of seconds which seem to get lost. I didn't know how
        > > to have it raise an event when data is present at the stream, so I setup a
        > > timer to poll the stream.
        > >
        > > I've tried using "streamReader.P eek() != null" but it hangs, I've tried just
        > > streamReader.Re adLine() but it hangs. Any suggestions are greatly
        > > appreciated. I'm using Beta 2[/color]
        >
        > Does the server flush the stream after sending the status code? It
        > sounds like it isn't, or that it's not sending a line terminator after
        > the status code.
        >
        > Have you tried using a network sniffer to check that the information is
        > coming over the wire?
        >
        > --
        > Jon Skeet - <skeet@pobox.co m>
        > http://www.pobox.com/~skeet
        > If replying to the group, please do not mail me too
        >[/color]

        Comment

        • JoKur

          #5
          Re: StreamReader not reading all lines

          Nicholas,

          Thanks for the suggestion. I had started by trying this approach but
          couldn't figure out how to get the polling thread to raise a message to the
          running program. Do you have any examples/samples of this?
          --
          Thanks
          Joe


          "Nicholas Paldino [.NET/C# MVP]" wrote:
          [color=blue]
          > JoKur,
          >
          > What I would do is have the StreamReader run in a loop, reading lines as
          > they come (it will hang in between). The key though is to have the
          > StreamReader run on another thread, which would raise an event when the
          > message is received. This way, you won't have to worry about hanging your
          > application, and can get notifications when the messages come in.
          >
          > Hope this helps.
          >
          >
          > --
          > - Nicholas Paldino [.NET/C# MVP]
          > - mvp@spam.guard. caspershouse.co m
          >
          > "JoKur" <Joe@JoKur.ne t> wrote in message
          > news:58910318-A143-474F-BC00-EB0CE2390597@mi crosoft.com...[color=green]
          > > Hello,
          > >
          > > First let me tell you that I'm very new to C# and learning as I go. I'm
          > > trying to write a client application to communicate with a server (that I
          > > didn't write). Each message from the server is on one line (\r\n at end)
          > > and
          > > is formed as [Message] [Optional Argument1] [Optional Argument2] - each of
          > > which is seperated by a space. Arguments with spaces in them are enclosed
          > > in
          > > quotations.
          > >
          > > So, I'm able to open a connection to the server. When I send a message to
          > > it, it immediately responds and I parse that using a
          > > streaReader.Rea dline().
          > > - That part works. The problem is that the server is also sending status
          > > messages every couple of seconds which seem to get lost. I didn't know
          > > how
          > > to have it raise an event when data is present at the stream, so I setup a
          > > timer to poll the stream.
          > >
          > > I've tried using "streamReader.P eek() != null" but it hangs, I've tried
          > > just
          > > streamReader.Re adLine() but it hangs. Any suggestions are greatly
          > > appreciated. I'm using Beta 2
          > >
          > > Code is below
          > >
          > > Thanks in advance!!
          > > Joe
          > >
          > >
          > > using System;
          > > using System.Componen tModel;
          > > using System.Data;
          > > using System.Drawing;
          > > using System.Text;
          > > using System.Windows. Forms;
          > > using System.Collecti ons;
          > > using System.Threadin g;
          > > using System.Net.Sock ets;
          > > using System.IO;
          > >
          > > public delegate void ConnectionHandl er(bool State);
          > > public delegate void ControlChangeHa ndler(String Message);
          > >
          > > public partial class MMConnection : Form
          > > {
          > >
          > > //--------------------------------------------------------------
          > > // Class Variables
          > > private NetworkStream netStream;
          > > private StreamWriter netWriter;
          > > private StreamReader netReader;
          > > public TcpClient netClient;
          > > private bool netClientStart = false;
          > > private bool netClientConnec ted = false;
          > >
          > > private System.Net.IPAd dress ipAddress =
          > > System.Net.IPAd dress.Parse("12 7.0.0.1");
          > > private int ipPort = 1632;
          > > private String strUsername = "Contempora ry";
          > > private String strPassword = "techspa";
          > > private bool blnLoggedIn = false;
          > >
          > > // Define events this class can raise
          > > public event ConnectionHandl er OnConnectionCha nged;
          > > public event ControlChangeHa ndler OnControlChange d;
          > >
          > > //--------------------------------------------------------------
          > > // Constructor
          > > public MMConnection()
          > > {
          > > InitializeCompo nent();
          > > }
          > >
          > > // Startup the client
          > > public void ConnectionStart ()
          > > {
          > > netClientStart = true;
          > > tmrStatus.Enabl ed = true;
          > > }
          > >
          > > public void ConnectionStop ()
          > > {
          > > try
          > > {
          > > logToScreen("Cl osing connection");
          > >
          > > // Close connection
          > > netWriter.Close ();
          > > netReader.Close ();
          > > netStream.Close ();
          > > netClient.Close ();
          > > }
          > > catch (Exception e)
          > > {
          > > logToScreen("Er ror closing connection: " + e.Message.ToStr ing());
          > > }
          > > }
          > >
          > > private void StreamWrite (string strMessage)
          > > {
          > > try
          > > {
          > > if (strMessage != "sg") logToScreen("Se nding string: " + strMessage);
          > > netWriter.Write (strMessage + "\r\n");
          > > netWriter.Flush ();
          > > }
          > > catch (Exception e)
          > > {
          > > netClientConnec ted = false; // Cannot send - client must have disconnected
          > > Console.WriteLi ne("Error sending string: " + e.Message.ToStr ing());
          > > }
          > > }
          > >
          > > public void MessageSend(str ing strMessage)
          > > {
          > > StreamWrite(str Message);
          > > }
          > >
          > > // Send Password to the server
          > > private void sendLogin()
          > > {
          > > StreamWrite("li " + " " + strUsername + " " + strPassword);
          > > }
          > >
          > > // Parse responses from the server
          > > private void ProcessString(S tring strData)
          > > {
          > > int foundPosition; //Position of the first space
          > > String firstToken; //The first token (command or error
          > >
          > > // Parse out the first token
          > > foundPosition = strData.IndexOf (@" ");
          > > if (foundPosition > -1)
          > > {
          > > firstToken = strData.Substri ng(0, foundPosition). ToString();
          > > }
          > > else
          > > {
          > > firstToken = strData.ToStrin g();
          > > }
          > >
          > > // Act on the first token
          > > switch (firstToken)
          > > {
          > > case "notLoggedI n":
          > > sendLogin();
          > > break;
          > >
          > > case "loggedIn":
          > > blnLoggedIn = true;
          > > logToScreen("Lo gged into MediaMatrix");
          > > UpdateConnectio nIndicator(netC lient.Connected );
          > > break;
          > >
          > > case "statusIs":
          > > blnLoggedIn = true;
          > > break;
          > >
          > > case "valueIs":
          > > OnControlChange d(strData);
          > > break;
          > >
          > > default: //no token
          > > break;
          > > }
          > > }
          > >
          > > private void tmrStatus_Tick( object sender, EventArgs e)
          > > {
          > > if (netClientConne cted)
          > > {
          > > tmrRead.Enabled = true;
          > > StreamWrite("sg "); //Status Get
          > > }
          > > else
          > > {
          > > if (netClientStart )
          > > {
          > > try
          > > {
          > >
          > > netClient = new TcpClient();
          > > // Create TcpClient and connect to server
          > > netClient.Conne ct(ipAddress, ipPort);
          > > //UpdateConnectio nIndicator(netC lient.Connected ); //Moved to after
          > > login
          > >
          > > // Get network Stream associated with TcpClient
          > > netStream = netClient.GetSt ream();
          > > netClientConnec ted = true;
          > > logToScreen("Co nnection Successfull to: " + ipAddress + " port: " +
          > > ipPort);
          > >
          > > // Create readers and writers
          > > netReader = new StreamReader(ne tStream);
          > > netWriter = new StreamWriter(ne tStream);
          > > Console.WriteLi ne("Got Streams!");
          > > }
          > > catch (Exception error)
          > > {
          > > Console.Write ("Error: " + error.ToString( ));
          > > netClientConnec ted = false;
          > > }
          > > }
          > > }
          > >
          > > // Update the color
          > > //UpdateConnectio nIndicator(netC lient.Connected );
          > > }
          > >
          > > private void logToScreen(Str ing strMessage)
          > > {
          > > lstReceive.Item s.Add(strMessag e);
          > > Console.WriteLi ne(strMessage);
          > > }
          > >
          > > private void btnSend_Click(o bject sender, EventArgs e)
          > > {
          > > StreamWrite(txt Send.Text);
          > > }
          > >
          > > private void tmrRead_Tick(ob ject sender, EventArgs e)
          > > {
          > > String strData;
          > >
          > > try
          > > {
          > > // Read and display lines from the network stream
          > > //while(netStream .DataAvailable)
          > > // logToScreen("En d of Stream: " + netReader.EndOf Stream);
          > > // logToScreen("Ne t Reader: " + netReader.ReadL ine().ToString( ));
          > > // logToScreen("En d of Stream: " + netReader.EndOf Stream);
          > > while (netStream.Data Available)
          > > {
          > > try
          > > {
          > > // Grab data from socket
          > > strData = netReader.ReadL ine();
          > >
          > > // Clean it up a bit
          > > strData = strData.Trim(ne w char[3] { '\a', '\r', '\n' });
          > >
          > > // Send it on to be parsed
          > > logToScreen("Re ceived string: " + strData);
          > > ProcessString(s trData);
          > > }
          > > catch (Exception ex)
          > > {
          > > logToScreen("Er ror reading string: " + ex.Message.ToSt ring());
          > > }
          > > }
          > > }
          > > catch (Exception exc)
          > > {
          > > logToScreen("Er ror Receiving: " + exc.Message.ToS tring());
          > > }
          > > }
          > >
          > > public static string[] Tokenize(string strIncoming)
          > > {
          > > //TODO: Put regular expresstion
          > > System.Text.Reg ularExpressions .Regex regFilter = new
          > > System.Text.Reg ularExpressions .Regex
          > > ( @"\a|\s" );
          > >
          > > return (regFilter.Spli t(strIncoming)) ;
          > > }
          > >
          > > private void UpdateConnectio nIndicator(bool blnConnected)
          > > {
          > > if (blnConnected)
          > > {
          > > staStripConnect ed.Text = "Connected" ;
          > > staStripConnect ed.BackColor = System.Drawing. Color.LightGree n;
          > > }
          > > else
          > > {
          > > staStripConnect ed.Text = "Not Connected";
          > > staStripConnect ed.BackColor = System.Drawing. Color.Red;
          > > }
          > >[/color][/color]

          Comment

          • Nicholas Paldino [.NET/C# MVP]

            #6
            Re: StreamReader not reading all lines

            JoKur,

            Why not just create an event, and when the call to ReadLine completes,
            fire the event. Then, you can attach any listener that you want. You just
            have to be careful, because the event will be fired on the thread that is
            doing the reading.


            --
            - Nicholas Paldino [.NET/C# MVP]
            - mvp@spam.guard. caspershouse.co m

            "JoKur" <Joe@JoKur.ne t> wrote in message
            news:785F7AFB-EC43-48A5-8112-AF86F458A880@mi crosoft.com...[color=blue]
            > Nicholas,
            >
            > Thanks for the suggestion. I had started by trying this approach but
            > couldn't figure out how to get the polling thread to raise a message to
            > the
            > running program. Do you have any examples/samples of this?
            > --
            > Thanks
            > Joe
            >
            >
            > "Nicholas Paldino [.NET/C# MVP]" wrote:
            >[color=green]
            >> JoKur,
            >>
            >> What I would do is have the StreamReader run in a loop, reading lines
            >> as
            >> they come (it will hang in between). The key though is to have the
            >> StreamReader run on another thread, which would raise an event when the
            >> message is received. This way, you won't have to worry about hanging
            >> your
            >> application, and can get notifications when the messages come in.
            >>
            >> Hope this helps.
            >>
            >>
            >> --
            >> - Nicholas Paldino [.NET/C# MVP]
            >> - mvp@spam.guard. caspershouse.co m
            >>
            >> "JoKur" <Joe@JoKur.ne t> wrote in message
            >> news:58910318-A143-474F-BC00-EB0CE2390597@mi crosoft.com...[color=darkred]
            >> > Hello,
            >> >
            >> > First let me tell you that I'm very new to C# and learning as I go.
            >> > I'm
            >> > trying to write a client application to communicate with a server (that
            >> > I
            >> > didn't write). Each message from the server is on one line (\r\n at
            >> > end)
            >> > and
            >> > is formed as [Message] [Optional Argument1] [Optional Argument2] - each
            >> > of
            >> > which is seperated by a space. Arguments with spaces in them are
            >> > enclosed
            >> > in
            >> > quotations.
            >> >
            >> > So, I'm able to open a connection to the server. When I send a message
            >> > to
            >> > it, it immediately responds and I parse that using a
            >> > streaReader.Rea dline().
            >> > - That part works. The problem is that the server is also sending
            >> > status
            >> > messages every couple of seconds which seem to get lost. I didn't know
            >> > how
            >> > to have it raise an event when data is present at the stream, so I
            >> > setup a
            >> > timer to poll the stream.
            >> >
            >> > I've tried using "streamReader.P eek() != null" but it hangs, I've tried
            >> > just
            >> > streamReader.Re adLine() but it hangs. Any suggestions are greatly
            >> > appreciated. I'm using Beta 2
            >> >
            >> > Code is below
            >> >
            >> > Thanks in advance!!
            >> > Joe
            >> >
            >> >
            >> > using System;
            >> > using System.Componen tModel;
            >> > using System.Data;
            >> > using System.Drawing;
            >> > using System.Text;
            >> > using System.Windows. Forms;
            >> > using System.Collecti ons;
            >> > using System.Threadin g;
            >> > using System.Net.Sock ets;
            >> > using System.IO;
            >> >
            >> > public delegate void ConnectionHandl er(bool State);
            >> > public delegate void ControlChangeHa ndler(String Message);
            >> >
            >> > public partial class MMConnection : Form
            >> > {
            >> >
            >> > //--------------------------------------------------------------
            >> > // Class Variables
            >> > private NetworkStream netStream;
            >> > private StreamWriter netWriter;
            >> > private StreamReader netReader;
            >> > public TcpClient netClient;
            >> > private bool netClientStart = false;
            >> > private bool netClientConnec ted = false;
            >> >
            >> > private System.Net.IPAd dress ipAddress =
            >> > System.Net.IPAd dress.Parse("12 7.0.0.1");
            >> > private int ipPort = 1632;
            >> > private String strUsername = "Contempora ry";
            >> > private String strPassword = "techspa";
            >> > private bool blnLoggedIn = false;
            >> >
            >> > // Define events this class can raise
            >> > public event ConnectionHandl er OnConnectionCha nged;
            >> > public event ControlChangeHa ndler OnControlChange d;
            >> >
            >> > //--------------------------------------------------------------
            >> > // Constructor
            >> > public MMConnection()
            >> > {
            >> > InitializeCompo nent();
            >> > }
            >> >
            >> > // Startup the client
            >> > public void ConnectionStart ()
            >> > {
            >> > netClientStart = true;
            >> > tmrStatus.Enabl ed = true;
            >> > }
            >> >
            >> > public void ConnectionStop ()
            >> > {
            >> > try
            >> > {
            >> > logToScreen("Cl osing connection");
            >> >
            >> > // Close connection
            >> > netWriter.Close ();
            >> > netReader.Close ();
            >> > netStream.Close ();
            >> > netClient.Close ();
            >> > }
            >> > catch (Exception e)
            >> > {
            >> > logToScreen("Er ror closing connection: " + e.Message.ToStr ing());
            >> > }
            >> > }
            >> >
            >> > private void StreamWrite (string strMessage)
            >> > {
            >> > try
            >> > {
            >> > if (strMessage != "sg") logToScreen("Se nding string: " + strMessage);
            >> > netWriter.Write (strMessage + "\r\n");
            >> > netWriter.Flush ();
            >> > }
            >> > catch (Exception e)
            >> > {
            >> > netClientConnec ted = false; // Cannot send - client must have
            >> > disconnected
            >> > Console.WriteLi ne("Error sending string: " + e.Message.ToStr ing());
            >> > }
            >> > }
            >> >
            >> > public void MessageSend(str ing strMessage)
            >> > {
            >> > StreamWrite(str Message);
            >> > }
            >> >
            >> > // Send Password to the server
            >> > private void sendLogin()
            >> > {
            >> > StreamWrite("li " + " " + strUsername + " " + strPassword);
            >> > }
            >> >
            >> > // Parse responses from the server
            >> > private void ProcessString(S tring strData)
            >> > {
            >> > int foundPosition; //Position of the first space
            >> > String firstToken; //The first token (command or error
            >> >
            >> > // Parse out the first token
            >> > foundPosition = strData.IndexOf (@" ");
            >> > if (foundPosition > -1)
            >> > {
            >> > firstToken = strData.Substri ng(0, foundPosition). ToString();
            >> > }
            >> > else
            >> > {
            >> > firstToken = strData.ToStrin g();
            >> > }
            >> >
            >> > // Act on the first token
            >> > switch (firstToken)
            >> > {
            >> > case "notLoggedI n":
            >> > sendLogin();
            >> > break;
            >> >
            >> > case "loggedIn":
            >> > blnLoggedIn = true;
            >> > logToScreen("Lo gged into MediaMatrix");
            >> > UpdateConnectio nIndicator(netC lient.Connected );
            >> > break;
            >> >
            >> > case "statusIs":
            >> > blnLoggedIn = true;
            >> > break;
            >> >
            >> > case "valueIs":
            >> > OnControlChange d(strData);
            >> > break;
            >> >
            >> > default: //no token
            >> > break;
            >> > }
            >> > }
            >> >
            >> > private void tmrStatus_Tick( object sender, EventArgs e)
            >> > {
            >> > if (netClientConne cted)
            >> > {
            >> > tmrRead.Enabled = true;
            >> > StreamWrite("sg "); //Status Get
            >> > }
            >> > else
            >> > {
            >> > if (netClientStart )
            >> > {
            >> > try
            >> > {
            >> >
            >> > netClient = new TcpClient();
            >> > // Create TcpClient and connect to server
            >> > netClient.Conne ct(ipAddress, ipPort);
            >> > //UpdateConnectio nIndicator(netC lient.Connected ); //Moved to after
            >> > login
            >> >
            >> > // Get network Stream associated with TcpClient
            >> > netStream = netClient.GetSt ream();
            >> > netClientConnec ted = true;
            >> > logToScreen("Co nnection Successfull to: " + ipAddress + " port: " +
            >> > ipPort);
            >> >
            >> > // Create readers and writers
            >> > netReader = new StreamReader(ne tStream);
            >> > netWriter = new StreamWriter(ne tStream);
            >> > Console.WriteLi ne("Got Streams!");
            >> > }
            >> > catch (Exception error)
            >> > {
            >> > Console.Write ("Error: " + error.ToString( ));
            >> > netClientConnec ted = false;
            >> > }
            >> > }
            >> > }
            >> >
            >> > // Update the color
            >> > //UpdateConnectio nIndicator(netC lient.Connected );
            >> > }
            >> >
            >> > private void logToScreen(Str ing strMessage)
            >> > {
            >> > lstReceive.Item s.Add(strMessag e);
            >> > Console.WriteLi ne(strMessage);
            >> > }
            >> >
            >> > private void btnSend_Click(o bject sender, EventArgs e)
            >> > {
            >> > StreamWrite(txt Send.Text);
            >> > }
            >> >
            >> > private void tmrRead_Tick(ob ject sender, EventArgs e)
            >> > {
            >> > String strData;
            >> >
            >> > try
            >> > {
            >> > // Read and display lines from the network stream
            >> > //while(netStream .DataAvailable)
            >> > // logToScreen("En d of Stream: " + netReader.EndOf Stream);
            >> > // logToScreen("Ne t Reader: " + netReader.ReadL ine().ToString( ));
            >> > // logToScreen("En d of Stream: " + netReader.EndOf Stream);
            >> > while (netStream.Data Available)
            >> > {
            >> > try
            >> > {
            >> > // Grab data from socket
            >> > strData = netReader.ReadL ine();
            >> >
            >> > // Clean it up a bit
            >> > strData = strData.Trim(ne w char[3] { '\a', '\r', '\n' });
            >> >
            >> > // Send it on to be parsed
            >> > logToScreen("Re ceived string: " + strData);
            >> > ProcessString(s trData);
            >> > }
            >> > catch (Exception ex)
            >> > {
            >> > logToScreen("Er ror reading string: " + ex.Message.ToSt ring());
            >> > }
            >> > }
            >> > }
            >> > catch (Exception exc)
            >> > {
            >> > logToScreen("Er ror Receiving: " + exc.Message.ToS tring());
            >> > }
            >> > }
            >> >
            >> > public static string[] Tokenize(string strIncoming)
            >> > {
            >> > //TODO: Put regular expresstion
            >> > System.Text.Reg ularExpressions .Regex regFilter = new
            >> > System.Text.Reg ularExpressions .Regex
            >> > ( @"\a|\s" );
            >> >
            >> > return (regFilter.Spli t(strIncoming)) ;
            >> > }
            >> >
            >> > private void UpdateConnectio nIndicator(bool blnConnected)
            >> > {
            >> > if (blnConnected)
            >> > {
            >> > staStripConnect ed.Text = "Connected" ;
            >> > staStripConnect ed.BackColor = System.Drawing. Color.LightGree n;
            >> > }
            >> > else
            >> > {
            >> > staStripConnect ed.Text = "Not Connected";
            >> > staStripConnect ed.BackColor = System.Drawing. Color.Red;
            >> > }
            >> >[/color][/color][/color]


            Comment

            • Jon Skeet [C# MVP]

              #7
              Re: StreamReader not reading all lines

              JoKur <Joe@JoKur.ne t> wrote:[color=blue]
              > It ends each line with \r\n, which is supposedly what ReadLine() looks for.
              > I can see this when I connect using Telnet.
              >
              > I had another thought, is it possible that the server is sending more than
              > one line but when I'm reading them, I'm only grabbing the first line?
              >
              > In other words... What happens if I'm accessing the stream (like writing to
              > it), when something else comes in? Is there a way to ask how many lines it
              > sees and then do a ReadLine() for each one?[/color]

              Just calling ReadLine repeatedly should be fine. It doesn't matter if
              you're writing when the line comes in - it will buffer the input.

              --
              Jon Skeet - <skeet@pobox.co m>
              Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

              If replying to the group, please do not mail me too

              Comment

              • JoKur

                #8
                Re: StreamReader not reading all lines

                Being as I'm so new to C#, can you give an example of this?
                --
                Thanks
                Joe


                "Nicholas Paldino [.NET/C# MVP]" wrote:
                [color=blue]
                > JoKur,
                >
                > Why not just create an event, and when the call to ReadLine completes,
                > fire the event. Then, you can attach any listener that you want. You just
                > have to be careful, because the event will be fired on the thread that is
                > doing the reading.
                >
                >
                > --
                > - Nicholas Paldino [.NET/C# MVP]
                > - mvp@spam.guard. caspershouse.co m
                >
                > "JoKur" <Joe@JoKur.ne t> wrote in message
                > news:785F7AFB-EC43-48A5-8112-AF86F458A880@mi crosoft.com...[color=green]
                > > Nicholas,
                > >
                > > Thanks for the suggestion. I had started by trying this approach but
                > > couldn't figure out how to get the polling thread to raise a message to
                > > the
                > > running program. Do you have any examples/samples of this?
                > > --
                > > Thanks
                > > Joe
                > >
                > >
                > > "Nicholas Paldino [.NET/C# MVP]" wrote:
                > >[color=darkred]
                > >> JoKur,
                > >>
                > >> What I would do is have the StreamReader run in a loop, reading lines
                > >> as
                > >> they come (it will hang in between). The key though is to have the
                > >> StreamReader run on another thread, which would raise an event when the
                > >> message is received. This way, you won't have to worry about hanging
                > >> your
                > >> application, and can get notifications when the messages come in.
                > >>
                > >> Hope this helps.
                > >>
                > >>
                > >> --
                > >> - Nicholas Paldino [.NET/C# MVP]
                > >> - mvp@spam.guard. caspershouse.co m
                > >>
                > >> "JoKur" <Joe@JoKur.ne t> wrote in message
                > >> news:58910318-A143-474F-BC00-EB0CE2390597@mi crosoft.com...
                > >> > Hello,
                > >> >
                > >> > First let me tell you that I'm very new to C# and learning as I go.
                > >> > I'm
                > >> > trying to write a client application to communicate with a server (that
                > >> > I
                > >> > didn't write). Each message from the server is on one line (\r\n at
                > >> > end)
                > >> > and
                > >> > is formed as [Message] [Optional Argument1] [Optional Argument2] - each
                > >> > of
                > >> > which is seperated by a space. Arguments with spaces in them are
                > >> > enclosed
                > >> > in
                > >> > quotations.
                > >> >
                > >> > So, I'm able to open a connection to the server. When I send a message
                > >> > to
                > >> > it, it immediately responds and I parse that using a
                > >> > streaReader.Rea dline().
                > >> > - That part works. The problem is that the server is also sending
                > >> > status
                > >> > messages every couple of seconds which seem to get lost. I didn't know
                > >> > how
                > >> > to have it raise an event when data is present at the stream, so I
                > >> > setup a
                > >> > timer to poll the stream.
                > >> >
                > >> > I've tried using "streamReader.P eek() != null" but it hangs, I've tried
                > >> > just
                > >> > streamReader.Re adLine() but it hangs. Any suggestions are greatly
                > >> > appreciated. I'm using Beta 2
                > >> >
                > >> > Code is below
                > >> >
                > >> > Thanks in advance!!
                > >> > Joe
                > >> >
                > >> >
                > >> > using System;
                > >> > using System.Componen tModel;
                > >> > using System.Data;
                > >> > using System.Drawing;
                > >> > using System.Text;
                > >> > using System.Windows. Forms;
                > >> > using System.Collecti ons;
                > >> > using System.Threadin g;
                > >> > using System.Net.Sock ets;
                > >> > using System.IO;
                > >> >
                > >> > public delegate void ConnectionHandl er(bool State);
                > >> > public delegate void ControlChangeHa ndler(String Message);
                > >> >
                > >> > public partial class MMConnection : Form
                > >> > {
                > >> >
                > >> > //--------------------------------------------------------------
                > >> > // Class Variables
                > >> > private NetworkStream netStream;
                > >> > private StreamWriter netWriter;
                > >> > private StreamReader netReader;
                > >> > public TcpClient netClient;
                > >> > private bool netClientStart = false;
                > >> > private bool netClientConnec ted = false;
                > >> >
                > >> > private System.Net.IPAd dress ipAddress =
                > >> > System.Net.IPAd dress.Parse("12 7.0.0.1");
                > >> > private int ipPort = 1632;
                > >> > private String strUsername = "Contempora ry";
                > >> > private String strPassword = "techspa";
                > >> > private bool blnLoggedIn = false;
                > >> >
                > >> > // Define events this class can raise
                > >> > public event ConnectionHandl er OnConnectionCha nged;
                > >> > public event ControlChangeHa ndler OnControlChange d;
                > >> >
                > >> > //--------------------------------------------------------------
                > >> > // Constructor
                > >> > public MMConnection()
                > >> > {
                > >> > InitializeCompo nent();
                > >> > }
                > >> >
                > >> > // Startup the client
                > >> > public void ConnectionStart ()
                > >> > {
                > >> > netClientStart = true;
                > >> > tmrStatus.Enabl ed = true;
                > >> > }
                > >> >
                > >> > public void ConnectionStop ()
                > >> > {
                > >> > try
                > >> > {
                > >> > logToScreen("Cl osing connection");
                > >> >
                > >> > // Close connection
                > >> > netWriter.Close ();
                > >> > netReader.Close ();
                > >> > netStream.Close ();
                > >> > netClient.Close ();
                > >> > }
                > >> > catch (Exception e)
                > >> > {
                > >> > logToScreen("Er ror closing connection: " + e.Message.ToStr ing());
                > >> > }
                > >> > }
                > >> >
                > >> > private void StreamWrite (string strMessage)
                > >> > {
                > >> > try
                > >> > {
                > >> > if (strMessage != "sg") logToScreen("Se nding string: " + strMessage);
                > >> > netWriter.Write (strMessage + "\r\n");
                > >> > netWriter.Flush ();
                > >> > }
                > >> > catch (Exception e)
                > >> > {
                > >> > netClientConnec ted = false; // Cannot send - client must have
                > >> > disconnected
                > >> > Console.WriteLi ne("Error sending string: " + e.Message.ToStr ing());
                > >> > }
                > >> > }
                > >> >
                > >> > public void MessageSend(str ing strMessage)
                > >> > {
                > >> > StreamWrite(str Message);
                > >> > }
                > >> >
                > >> > // Send Password to the server
                > >> > private void sendLogin()
                > >> > {
                > >> > StreamWrite("li " + " " + strUsername + " " + strPassword);
                > >> > }
                > >> >
                > >> > // Parse responses from the server
                > >> > private void ProcessString(S tring strData)
                > >> > {
                > >> > int foundPosition; //Position of the first space
                > >> > String firstToken; //The first token (command or error
                > >> >
                > >> > // Parse out the first token
                > >> > foundPosition = strData.IndexOf (@" ");
                > >> > if (foundPosition > -1)
                > >> > {
                > >> > firstToken = strData.Substri ng(0, foundPosition). ToString();
                > >> > }
                > >> > else
                > >> > {
                > >> > firstToken = strData.ToStrin g();
                > >> > }
                > >> >
                > >> > // Act on the first token
                > >> > switch (firstToken)
                > >> > {
                > >> > case "notLoggedI n":
                > >> > sendLogin();
                > >> > break;
                > >> >
                > >> > case "loggedIn":
                > >> > blnLoggedIn = true;
                > >> > logToScreen("Lo gged into MediaMatrix");
                > >> > UpdateConnectio nIndicator(netC lient.Connected );
                > >> > break;
                > >> >
                > >> > case "statusIs":
                > >> > blnLoggedIn = true;
                > >> > break;
                > >> >
                > >> > case "valueIs":
                > >> > OnControlChange d(strData);
                > >> > break;
                > >> >
                > >> > default: //no token
                > >> > break;
                > >> > }
                > >> > }
                > >> >
                > >> > private void tmrStatus_Tick( object sender, EventArgs e)
                > >> > {
                > >> > if (netClientConne cted)
                > >> > {
                > >> > tmrRead.Enabled = true;
                > >> > StreamWrite("sg "); //Status Get
                > >> > }
                > >> > else
                > >> > {
                > >> > if (netClientStart )
                > >> > {
                > >> > try
                > >> > {
                > >> >
                > >> > netClient = new TcpClient();
                > >> > // Create TcpClient and connect to server
                > >> > netClient.Conne ct(ipAddress, ipPort);
                > >> > //UpdateConnectio nIndicator(netC lient.Connected ); //Moved to after
                > >> > login
                > >> >
                > >> > // Get network Stream associated with TcpClient
                > >> > netStream = netClient.GetSt ream();
                > >> > netClientConnec ted = true;
                > >> > logToScreen("Co nnection Successfull to: " + ipAddress + " port: " +
                > >> > ipPort);
                > >> >
                > >> > // Create readers and writers
                > >> > netReader = new StreamReader(ne tStream);
                > >> > netWriter = new StreamWriter(ne tStream);
                > >> > Console.WriteLi ne("Got Streams!");
                > >> > }
                > >> > catch (Exception error)
                > >> > {
                > >> > Console.Write ("Error: " + error.ToString( ));
                > >> > netClientConnec ted = false;
                > >> > }
                > >> > }
                > >> > }
                > >> >
                > >> > // Update the color
                > >> > //UpdateConnectio nIndicator(netC lient.Connected );
                > >> > }
                > >> >
                > >> > private void logToScreen(Str ing strMessage)
                > >> > {
                > >> > lstReceive.Item s.Add(strMessag e);
                > >> > Console.WriteLi ne(strMessage);
                > >> > }
                > >> >
                > >> > private void btnSend_Click(o bject sender, EventArgs e)
                > >> > {
                > >> > StreamWrite(txt Send.Text);
                > >> > }
                > >> >
                > >> > private void tmrRead_Tick(ob ject sender, EventArgs e)
                > >> > {
                > >> > String strData;
                > >> >
                > >> > try
                > >> > {
                > >> > // Read and display lines from the network stream
                > >> > //while(netStream .DataAvailable)
                > >> > // logToScreen("En d of Stream: " + netReader.EndOf Stream);
                > >> > // logToScreen("Ne t Reader: " + netReader.ReadL ine().ToString( ));
                > >> > // logToScreen("En d of Stream: " + netReader.EndOf Stream);
                > >> > while (netStream.Data Available)
                > >> > {
                > >> > try
                > >> > {
                > >> > // Grab data from socket
                > >> > strData = netReader.ReadL ine();
                > >> >
                > >> > // Clean it up a bit
                > >> > strData = strData.Trim(ne w char[3] { '\a', '\r', '\n' });
                > >> >
                > >> > // Send it on to be parsed[/color][/color][/color]

                Comment

                • JoKur

                  #9
                  Re: StreamReader not reading all lines

                  I thought it should be fine too, but ReadLine() hangs when there's no data
                  currently in the stream. Any suggestions?
                  --
                  Thanks
                  Joe


                  "Jon Skeet [C# MVP]" wrote:
                  [color=blue]
                  > JoKur <Joe@JoKur.ne t> wrote:[color=green]
                  > > It ends each line with \r\n, which is supposedly what ReadLine() looks for.
                  > > I can see this when I connect using Telnet.
                  > >
                  > > I had another thought, is it possible that the server is sending more than
                  > > one line but when I'm reading them, I'm only grabbing the first line?
                  > >
                  > > In other words... What happens if I'm accessing the stream (like writing to
                  > > it), when something else comes in? Is there a way to ask how many lines it
                  > > sees and then do a ReadLine() for each one?[/color]
                  >
                  > Just calling ReadLine repeatedly should be fine. It doesn't matter if
                  > you're writing when the line comes in - it will buffer the input.
                  >
                  > --
                  > Jon Skeet - <skeet@pobox.co m>
                  > http://www.pobox.com/~skeet
                  > If replying to the group, please do not mail me too
                  >[/color]

                  Comment

                  • Jon Skeet [C# MVP]

                    #10
                    Re: StreamReader not reading all lines

                    JoKur <Joe@JoKur.ne t> wrote:[color=blue]
                    > I thought it should be fine too, but ReadLine() hangs when there's no data
                    > currently in the stream. Any suggestions?[/color]

                    It's *meant* to block when there's no data in the stream. I don't see
                    why that's a problem - if it is, then it sounds like you need to
                    process the incoming stream in another thread.

                    --
                    Jon Skeet - <skeet@pobox.co m>
                    Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

                    If replying to the group, please do not mail me too

                    Comment

                    • JoKur

                      #11
                      Re: StreamReader not reading all lines

                      Sorry, maybe I'm too much of a newbie to understand what you mean by 'block'.
                      What happens is the app just freezes (without throwing any exception) when
                      there is no data. It never resumes, even when new data has been put into the
                      stream.

                      The help file on StreamReader.Re adLine() says to do this...

                      using (StreamReader sr = new StreamReader(pa th))
                      {
                      while (sr.Peek() >= 0)
                      {
                      Console.WriteLi ne(sr.ReadLine( ));
                      }
                      }

                      When I try to use Peek(), it hang too. Same thing - never resumes, just
                      freezes right there. So, are the StreamReaders meant to be used with
                      TCPClient? If not, how should I change my app to make these things work?

                      If what your saying is true, and these functions are performing as they are
                      'meant' to, then I'll have to sense when the tread is hung and start a new
                      thread? Is that right? ...and if I'm starting a new thread everytime one
                      hangs (which will be about 10 X per second) what happens to the old threads?
                      (isn't that somewhat like a memory leak?).

                      Thank you for your time, I'm just so confused!!

                      --
                      Thanks
                      Joe


                      "Jon Skeet [C# MVP]" wrote:
                      [color=blue]
                      > JoKur <Joe@JoKur.ne t> wrote:[color=green]
                      > > I thought it should be fine too, but ReadLine() hangs when there's no data
                      > > currently in the stream. Any suggestions?[/color]
                      >
                      > It's *meant* to block when there's no data in the stream. I don't see
                      > why that's a problem - if it is, then it sounds like you need to
                      > process the incoming stream in another thread.
                      >
                      > --
                      > Jon Skeet - <skeet@pobox.co m>
                      > http://www.pobox.com/~skeet
                      > If replying to the group, please do not mail me too
                      >[/color]

                      Comment

                      • Jon Skeet [C# MVP]

                        #12
                        Re: StreamReader not reading all lines

                        JoKur <Joe@JoKur.ne t> wrote:[color=blue]
                        > Sorry, maybe I'm too much of a newbie to understand what you mean by 'block'.
                        > What happens is the app just freezes (without throwing any exception) when
                        > there is no data. It never resumes, even when new data has been put into the
                        > stream.[/color]

                        If a line ending has gone into the stream (and been flushed
                        appropriately), it should definitely read that.
                        [color=blue]
                        > The help file on StreamReader.Re adLine() says to do this...
                        >
                        > using (StreamReader sr = new StreamReader(pa th))
                        > {
                        > while (sr.Peek() >= 0)
                        > {
                        > Console.WriteLi ne(sr.ReadLine( ));
                        > }
                        > }[/color]

                        I'd avoid using Peek myself. Instead, use the fact that ReadLine
                        returns null when it's finished.
                        [color=blue]
                        > When I try to use Peek(), it hang too. Same thing - never resumes, just
                        > freezes right there. So, are the StreamReaders meant to be used with
                        > TCPClient? If not, how should I change my app to make these things work?[/color]

                        It sounds like the server isn't flushing data or something similar.
                        [color=blue]
                        > If what your saying is true, and these functions are performing as they are
                        > 'meant' to, then I'll have to sense when the tread is hung and start a new
                        > thread? Is that right? ...and if I'm starting a new thread everytime one
                        > hangs (which will be about 10 X per second) what happens to the old threads?
                        > (isn't that somewhat like a memory leak?).[/color]

                        You'll be leaking threads - definitely not a good idea. It really
                        sounds like the server isn't behaving as you expect it to. You should
                        hook up a network monitor to see what's coming back.

                        --
                        Jon Skeet - <skeet@pobox.co m>
                        Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

                        If replying to the group, please do not mail me too

                        Comment

                        • Cool Guy

                          #13
                          Re: StreamReader not reading all lines

                          JoKur <Joe@JoKur.ne t> wrote:
                          [color=blue]
                          > If what your saying is true, and these functions are performing as they are
                          > 'meant' to, then I'll have to sense when the tread is hung and start a new
                          > thread? Is that right? ...and if I'm starting a new thread everytime one
                          > hangs (which will be about 10 X per second) what happens to the old threads?
                          > (isn't that somewhat like a memory leak?).[/color]

                          The problem with your current approach is that, since you call
                          StreamReader.Re adLine in the main (GUI) thread, the GUI will freeze when
                          there isn't currently a line to be read (ReadLine halts execution of the
                          thread on which it was called until there's a line to be read).

                          One way of solving this problem would be to create a background thread and
                          call ReadLine in that, over and over until the application has been closed,
                          notifying the GUI thread of data arrival via events. Then if ReadLine
                          doesn't return immediately, your GUI will not freeze.

                          I'd recommend that you read this:
                          <http://www.pobox.com/~skeet/csharp/threads/>.

                          Comment

                          • JoKur

                            #14
                            Re: StreamReader not reading all lines

                            Oh hey! I didn't see the link at the bottom of your message... Thanks!
                            --
                            Thanks
                            Joe


                            "Cool Guy" wrote:
                            [color=blue]
                            > JoKur <Joe@JoKur.ne t> wrote:
                            >[color=green]
                            > > If what your saying is true, and these functions are performing as they are
                            > > 'meant' to, then I'll have to sense when the tread is hung and start a new
                            > > thread? Is that right? ...and if I'm starting a new thread everytime one
                            > > hangs (which will be about 10 X per second) what happens to the old threads?
                            > > (isn't that somewhat like a memory leak?).[/color]
                            >
                            > The problem with your current approach is that, since you call
                            > StreamReader.Re adLine in the main (GUI) thread, the GUI will freeze when
                            > there isn't currently a line to be read (ReadLine halts execution of the
                            > thread on which it was called until there's a line to be read).
                            >
                            > One way of solving this problem would be to create a background thread and
                            > call ReadLine in that, over and over until the application has been closed,
                            > notifying the GUI thread of data arrival via events. Then if ReadLine
                            > doesn't return immediately, your GUI will not freeze.
                            >
                            > I'd recommend that you read this:
                            > <http://www.pobox.com/~skeet/csharp/threads/>.
                            >[/color]

                            Comment

                            • JoKur

                              #15
                              Re: StreamReader not reading all lines

                              Thanks, that's what Nicholas was suggesting also. The problem is I don't
                              know how to do that. Can you give me an example of creating a thread and
                              having it raise events? ...or at least point me to some more reading?
                              --
                              Thanks
                              Joe


                              "Cool Guy" wrote:
                              [color=blue]
                              > JoKur <Joe@JoKur.ne t> wrote:
                              >[color=green]
                              > > If what your saying is true, and these functions are performing as they are
                              > > 'meant' to, then I'll have to sense when the tread is hung and start a new
                              > > thread? Is that right? ...and if I'm starting a new thread everytime one
                              > > hangs (which will be about 10 X per second) what happens to the old threads?
                              > > (isn't that somewhat like a memory leak?).[/color]
                              >
                              > The problem with your current approach is that, since you call
                              > StreamReader.Re adLine in the main (GUI) thread, the GUI will freeze when
                              > there isn't currently a line to be read (ReadLine halts execution of the
                              > thread on which it was called until there's a line to be read).
                              >
                              > One way of solving this problem would be to create a background thread and
                              > call ReadLine in that, over and over until the application has been closed,
                              > notifying the GUI thread of data arrival via events. Then if ReadLine
                              > doesn't return immediately, your GUI will not freeze.
                              >
                              > I'd recommend that you read this:
                              > <http://www.pobox.com/~skeet/csharp/threads/>.
                              >[/color]

                              Comment

                              Working...