G
Guest
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.Readline().
- 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.Peek() != null" but it hangs, I've tried just
streamReader.ReadLine() but it hangs. Any suggestions are greatly
appreciated. I'm using Beta 2
Code is below
Thanks in advance!!
Joe
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Threading;
using System.Net.Sockets;
using System.IO;
public delegate void ConnectionHandler(bool State);
public delegate void ControlChangeHandler(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 netClientConnected = false;
private System.Net.IPAddress ipAddress =
System.Net.IPAddress.Parse("127.0.0.1");
private int ipPort = 1632;
private String strUsername = "Contemporary";
private String strPassword = "techspa";
private bool blnLoggedIn = false;
// Define events this class can raise
public event ConnectionHandler OnConnectionChanged;
public event ControlChangeHandler OnControlChanged;
//--------------------------------------------------------------
// Constructor
public MMConnection()
{
InitializeComponent();
}
// Startup the client
public void ConnectionStart()
{
netClientStart = true;
tmrStatus.Enabled = true;
}
public void ConnectionStop ()
{
try
{
logToScreen("Closing connection");
// Close connection
netWriter.Close();
netReader.Close();
netStream.Close();
netClient.Close();
}
catch (Exception e)
{
logToScreen("Error closing connection: " + e.Message.ToString());
}
}
private void StreamWrite (string strMessage)
{
try
{
if (strMessage != "sg") logToScreen("Sending string: " + strMessage);
netWriter.Write(strMessage + "\r\n");
netWriter.Flush();
}
catch (Exception e)
{
netClientConnected = false; // Cannot send - client must have disconnected
Console.WriteLine("Error sending string: " + e.Message.ToString());
}
}
public void MessageSend(string strMessage)
{
StreamWrite(strMessage);
}
// Send Password to the server
private void sendLogin()
{
StreamWrite("li" + " " + strUsername + " " + strPassword);
}
// Parse responses from the server
private void ProcessString(String 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.Substring(0, foundPosition).ToString();
}
else
{
firstToken = strData.ToString();
}
// Act on the first token
switch (firstToken)
{
case "notLoggedIn":
sendLogin();
break;
case "loggedIn":
blnLoggedIn = true;
logToScreen("Logged into MediaMatrix");
UpdateConnectionIndicator(netClient.Connected);
break;
case "statusIs":
blnLoggedIn = true;
break;
case "valueIs":
OnControlChanged(strData);
break;
default: //no token
break;
}
}
private void tmrStatus_Tick(object sender, EventArgs e)
{
if (netClientConnected)
{
tmrRead.Enabled = true;
StreamWrite("sg"); //Status Get
}
else
{
if (netClientStart)
{
try
{
netClient = new TcpClient();
// Create TcpClient and connect to server
netClient.Connect(ipAddress, ipPort);
//UpdateConnectionIndicator(netClient.Connected); //Moved to after
login
// Get network Stream associated with TcpClient
netStream = netClient.GetStream();
netClientConnected = true;
logToScreen("Connection Successfull to: " + ipAddress + " port: " +
ipPort);
// Create readers and writers
netReader = new StreamReader(netStream);
netWriter = new StreamWriter(netStream);
Console.WriteLine("Got Streams!");
}
catch (Exception error)
{
Console.Write ("Error: " + error.ToString());
netClientConnected = false;
}
}
}
// Update the color
//UpdateConnectionIndicator(netClient.Connected);
}
private void logToScreen(String strMessage)
{
lstReceive.Items.Add(strMessage);
Console.WriteLine(strMessage);
}
private void btnSend_Click(object sender, EventArgs e)
{
StreamWrite(txtSend.Text);
}
private void tmrRead_Tick(object sender, EventArgs e)
{
String strData;
try
{
// Read and display lines from the network stream
//while(netStream.DataAvailable)
// logToScreen("End of Stream: " + netReader.EndOfStream);
// logToScreen("Net Reader: " + netReader.ReadLine().ToString());
// logToScreen("End of Stream: " + netReader.EndOfStream);
while (netStream.DataAvailable)
{
try
{
// Grab data from socket
strData = netReader.ReadLine();
// Clean it up a bit
strData = strData.Trim(new char[3] { '\a', '\r', '\n' });
// Send it on to be parsed
logToScreen("Received string: " + strData);
ProcessString(strData);
}
catch (Exception ex)
{
logToScreen("Error reading string: " + ex.Message.ToString());
}
}
}
catch (Exception exc)
{
logToScreen("Error Receiving: " + exc.Message.ToString());
}
}
public static string[] Tokenize(string strIncoming)
{
//TODO: Put regular expresstion
System.Text.RegularExpressions.Regex regFilter = new
System.Text.RegularExpressions.Regex
( @"\a|\s" );
return (regFilter.Split(strIncoming));
}
private void UpdateConnectionIndicator(bool blnConnected)
{
if (blnConnected)
{
staStripConnected.Text = "Connected";
staStripConnected.BackColor = System.Drawing.Color.LightGreen;
}
else
{
staStripConnected.Text = "Not Connected";
staStripConnected.BackColor = System.Drawing.Color.Red;
}
//Raise Event to calling form
OnConnectionChanged(blnConnected);
}
}// 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.Readline().
- 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.Peek() != null" but it hangs, I've tried just
streamReader.ReadLine() but it hangs. Any suggestions are greatly
appreciated. I'm using Beta 2
Code is below
Thanks in advance!!
Joe
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Threading;
using System.Net.Sockets;
using System.IO;
public delegate void ConnectionHandler(bool State);
public delegate void ControlChangeHandler(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 netClientConnected = false;
private System.Net.IPAddress ipAddress =
System.Net.IPAddress.Parse("127.0.0.1");
private int ipPort = 1632;
private String strUsername = "Contemporary";
private String strPassword = "techspa";
private bool blnLoggedIn = false;
// Define events this class can raise
public event ConnectionHandler OnConnectionChanged;
public event ControlChangeHandler OnControlChanged;
//--------------------------------------------------------------
// Constructor
public MMConnection()
{
InitializeComponent();
}
// Startup the client
public void ConnectionStart()
{
netClientStart = true;
tmrStatus.Enabled = true;
}
public void ConnectionStop ()
{
try
{
logToScreen("Closing connection");
// Close connection
netWriter.Close();
netReader.Close();
netStream.Close();
netClient.Close();
}
catch (Exception e)
{
logToScreen("Error closing connection: " + e.Message.ToString());
}
}
private void StreamWrite (string strMessage)
{
try
{
if (strMessage != "sg") logToScreen("Sending string: " + strMessage);
netWriter.Write(strMessage + "\r\n");
netWriter.Flush();
}
catch (Exception e)
{
netClientConnected = false; // Cannot send - client must have disconnected
Console.WriteLine("Error sending string: " + e.Message.ToString());
}
}
public void MessageSend(string strMessage)
{
StreamWrite(strMessage);
}
// Send Password to the server
private void sendLogin()
{
StreamWrite("li" + " " + strUsername + " " + strPassword);
}
// Parse responses from the server
private void ProcessString(String 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.Substring(0, foundPosition).ToString();
}
else
{
firstToken = strData.ToString();
}
// Act on the first token
switch (firstToken)
{
case "notLoggedIn":
sendLogin();
break;
case "loggedIn":
blnLoggedIn = true;
logToScreen("Logged into MediaMatrix");
UpdateConnectionIndicator(netClient.Connected);
break;
case "statusIs":
blnLoggedIn = true;
break;
case "valueIs":
OnControlChanged(strData);
break;
default: //no token
break;
}
}
private void tmrStatus_Tick(object sender, EventArgs e)
{
if (netClientConnected)
{
tmrRead.Enabled = true;
StreamWrite("sg"); //Status Get
}
else
{
if (netClientStart)
{
try
{
netClient = new TcpClient();
// Create TcpClient and connect to server
netClient.Connect(ipAddress, ipPort);
//UpdateConnectionIndicator(netClient.Connected); //Moved to after
login
// Get network Stream associated with TcpClient
netStream = netClient.GetStream();
netClientConnected = true;
logToScreen("Connection Successfull to: " + ipAddress + " port: " +
ipPort);
// Create readers and writers
netReader = new StreamReader(netStream);
netWriter = new StreamWriter(netStream);
Console.WriteLine("Got Streams!");
}
catch (Exception error)
{
Console.Write ("Error: " + error.ToString());
netClientConnected = false;
}
}
}
// Update the color
//UpdateConnectionIndicator(netClient.Connected);
}
private void logToScreen(String strMessage)
{
lstReceive.Items.Add(strMessage);
Console.WriteLine(strMessage);
}
private void btnSend_Click(object sender, EventArgs e)
{
StreamWrite(txtSend.Text);
}
private void tmrRead_Tick(object sender, EventArgs e)
{
String strData;
try
{
// Read and display lines from the network stream
//while(netStream.DataAvailable)
// logToScreen("End of Stream: " + netReader.EndOfStream);
// logToScreen("Net Reader: " + netReader.ReadLine().ToString());
// logToScreen("End of Stream: " + netReader.EndOfStream);
while (netStream.DataAvailable)
{
try
{
// Grab data from socket
strData = netReader.ReadLine();
// Clean it up a bit
strData = strData.Trim(new char[3] { '\a', '\r', '\n' });
// Send it on to be parsed
logToScreen("Received string: " + strData);
ProcessString(strData);
}
catch (Exception ex)
{
logToScreen("Error reading string: " + ex.Message.ToString());
}
}
}
catch (Exception exc)
{
logToScreen("Error Receiving: " + exc.Message.ToString());
}
}
public static string[] Tokenize(string strIncoming)
{
//TODO: Put regular expresstion
System.Text.RegularExpressions.Regex regFilter = new
System.Text.RegularExpressions.Regex
( @"\a|\s" );
return (regFilter.Split(strIncoming));
}
private void UpdateConnectionIndicator(bool blnConnected)
{
if (blnConnected)
{
staStripConnected.Text = "Connected";
staStripConnected.BackColor = System.Drawing.Color.LightGreen;
}
else
{
staStripConnected.Text = "Not Connected";
staStripConnected.BackColor = System.Drawing.Color.Red;
}
//Raise Event to calling form
OnConnectionChanged(blnConnected);
}
}// MMConnection end