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
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
Comment