我尝试过使用streamReader.Peek()!= null但它挂了,我试过了 netWriter.Close(); { staStripConnected.Text =" Not Connected"; staStripConnected.BackColor = System.Drawing.Color.Red; } //将事件提升到调用表格 OnConnectionChanged(blnConnected); } } // MMConnection结束 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 JoKur< ; Jo*@JoKur.net>写道:JoKur <Jo*@JoKur.net> wrote:首先让我告诉你,我对C#很新,并且在我学习的同时学习。我正在尝试编写一个客户端应用程序来与服务器进行通信(我没有写过)。来自服务器的每条消息都在一行(结尾为\\\\ n),形成为[Message] [Optional Argument1] [Optional Argument2] - 每个分别由一个分隔的空间。带有空格的参数括在引号中。 所以,我能够打开与服务器的连接。当我向发送消息时,它会立即响应并使用streaReader.Readline()解析它。 - 该部分有效。问题是服务器每隔几秒钟也会发送状态消息,这些消息似乎都会丢失。当流中存在数据时,我不知道如何让它引发事件,所以我设置了一个计时器来轮询流。 我''尝试使用streamReader.Peek()!= null但它挂了,我试过了刚刚读取的streamReader.ReadLine()但它挂了。任何建议都非常感谢。我正在使用Beta 2 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 服务器在发送状态代码后是否刷新流?它听起来好像是没有,或者它是在发送状态代码后没有发送行终止符。 您是否尝试使用网络嗅探器检查信息是否来自电汇? - Jon Skeet - < sk *** @ pobox.com> http: //www.pobox.com/~skeet 如果回复小组,请不要给我发邮件Does the server flush the stream after sending the status code? Itsounds like it isn''t, or that it''s not sending a line terminator afterthe status code.Have you tried using a network sniffer to check that the information iscoming over the wire?--Jon Skeet - <sk***@pobox.com> http://www.pobox.com/~skeetIf replying to the group, please do not mail me too Jon , 它以\\\\ n结束每一行,这应该是ReadLine()所寻找的。 当我连接时,我可以看到这一点使用Telnet。 我有另外一个想法,服务器发送的数据可能超过 一行,但是当我读它们时,我我只抓住第一线? 换句话说......如果我正在访问流程会发生什么(比如写信给 吧),当什么东西埃尔斯进来?有没有办法问一下它会看到多少行,然后为每一行做一个ReadLine()? - 谢谢 Joe " Jon Skeet [C#MVP]"写道: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 thanone 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 toit), when something else comes in? Is there a way to ask how many lines itsees and then do a ReadLine() for each one?--ThanksJoe"Jon Skeet [C# MVP]" wrote: JoKur< Jo*@JoKur.net>写道: JoKur <Jo*@JoKur.net> wrote:首先让我告诉你,我对C#很新,并且在我学习的同时学习。我正在尝试编写一个客户端应用程序来与服务器进行通信(我没有写过)。来自服务器的每条消息都在一行(结尾为\\\\ n),形成为[Message] [Optional Argument1] [Optional Argument2] - 每个分别由一个分隔的空间。带有空格的参数括在引号中。 所以,我能够打开与服务器的连接。当我向发送消息时,它会立即响应并使用streaReader.Readline()解析它。 - 该部分有效。问题是服务器每隔几秒钟也会发送状态消息,这些消息似乎都会丢失。当流中存在数据时,我不知道如何让它引发事件,所以我设置了一个计时器来轮询流。 我''尝试使用streamReader.Peek()!= null但它挂了,我试过了刚刚读取的streamReader.ReadLine()但它挂了。任何建议都非常感谢。我正在使用Beta 2 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 服务器是否在发送状态代码后刷新流?它听起来好像没有,或者说它不是在状态码后发送行终止符。 你是否尝试过使用网络嗅探器检查这些信息是通过网络传输的吗? - Jon Skeet - < sk *** @ pobox.com> http://www.pobox.com/~skeet 如果回复小组,请不要给我发邮件 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 - <sk***@pobox.com> http://www.pobox.com/~skeet If replying to the group, please do not mail me too 这篇关于StreamReader没有读取所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-06 03:43