StreamReader没有读取所有行 [英] StreamReader not reading all lines

查看:97
本文介绍了StreamReader没有读取所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,


首先让我告诉您,我对C#非常陌生并且随时随地学习。我是
试图写一个客户端应用程序与服务器进行通信(我没有写b
)。来自服务器的每条消息都在一行(最后是\\\\ n)和

形成为[Message] [Optional Argument1] [Optional Argument2] - 每个

由空格分隔。带有空格的参数包含在

报价中。


所以,我能够打开与服务器的连接。当我向

发送消息时,它立即响应并使用streaReader.Readline()解析它。

- 该部分有效。问题是服务器每隔几秒钟也会发送状态

消息,这些消息似乎都会丢失。当流中存在数据时,我不知道如何让它引发事件,所以我设置了一个

计时器来轮询流。


我尝试过使用streamReader.Peek()!= null但它挂起,我已经尝试了只是

streamReader.ReadLine()但它挂了。任何建议都非常值得赞赏。我正在使用Beta 2


代码如下


提前致谢!!

Joe

使用System;

使用System.ComponentModel;

使用System.Data;

使用System.Drawing;

使用System.Text;

使用System.Windows.Forms;

使用System.Collections;

使用System。线程化;

使用System.Net.Sockets;

使用System.IO;


public delegate void ConnectionHandler(bool State) ;

public delegate void ControlChangeHandler(String Message);


公共部分类MMConnection:表格

{


// ----------------------------------------- ---------------------

//类变量

private NetworkStream netStream;

私有StreamWriter netWriter;

私有StreamReader netReader;

public TcpClient netClient;

private bool netClientStart = false;

privat e 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;


//定义此类可以引发的事件

公共事件ConnectionHandler OnConnectionChanged;

公共事件ControlChangeHandler OnControlChanged;


// --------------------------- -----------------------------------

//构造函数

public MMConnection()

{

InitializeComponent();

}


//启动客户端

public void ConnectionStart()

{

netClientStart = true;

tmrStatus.Enabled = true;

}


public void ConnectionStop()

{

尝试

{

logToScreen(" Closing connection");


//关闭连接

netWriter.Close();

netReader.Close();

netStream.Close();

netClient.Close(); < br $>
}

catch(例外e)

{

logToScreen("关闭连接时出错:" + e.Message.ToString());

}

}


private void StreamWrite(string strMessage)

{

尝试

{

if(strMessage!=" sg")logToScreen("发送字符串:" ; + strMessage);

netWriter.Write(strMessage +" \\\\ n");

netWriter.Flush();

}

catch(例外e)

{

netClientConnected = false; //无法发送 - 客户端必须已断开连接

Console.WriteLine(发送字符串错误:" + e.Message.ToString());

}

}


public void MessageSend(string strMessage)

{

StreamWrite(strMessage);

}


//向服务器发送密码

private void sendLogin()

{

StreamWrite(" li" +"" + strUsername +"" + strPassword);

}


/ /解析来自服务器的响应

private void ProcessString(String strData)

{

int foundPosition; //第一个空格的位置

String firstToken; //第一个令牌(命令或错误


//解析第一个令牌

foundPosition = strData.IndexOf(@"");

if(foundPosition> -1)

{

firstToken = strData.Substring(0,foundPosition).ToString();

}

else

{

firstToken = strData.ToString();

}


//对第一个令牌采取行动

开关(firstToken)

{

case" notLoggedIn":

sendLogin();

break;


case" loggedIn":

blnLoggedIn = true;

logToScreen(登录MediaMatrix);

UpdateConnectionIndicator(netClient.Connected);

break;


case" statusIs":

blnLoggedIn = true;

休息;


case" valueIs":

OnControlChanged(strData);

break;


默认值://无令牌

休息; < br $>
}

}


private void tmrStatus_Tick(对象发送者,EventArgs e)

{

if(netClientConnected)

{

tmrRead.Enabled = true;

StreamWrite(" sg"); //状态获取

}

其他

{

if(netClientStart)

{

试试

{


netClient = new TcpClient();

//创建TcpClient并连接到服务器

netClient.Connect(ipAddress,ipPort);

//UpdateConnectionIndicator(netClient.Connected); //移动到

登录后


//获取与TcpClient关联的网络流

netStream = netClient.GetStream();

netClientConnected = true;

logToScreen(" Connection Successfull to:" + ipAddress +" port:" +

ipPort) ;


//创建读者和作者

netReader = new StreamReader(netStream);

netWriter = new StreamWriter(netStream) ;

Console.WriteLine(" Got Streams!");

}

catch(异常错误)

{

Console.Write(" Error:" + error.ToString());

netClientConnected = false;

}

}

}


//更新颜色

//UpdateConnectionIndicator(netClient.Connected ); b / b $

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;


试试

{

//从网络流中读取和显示行

// (netStream.DataAvailable)

// logToScreen(" End of Stream:" + netReader.EndOfStream);

// logToScreen(" Net Reader:" + netReader.ReadLine()。ToString());

// logToScreen(" ; End of Stream:" + netReader.EndOfStream);

while(netStream.DataAvailable)

{

try

{

//从套接字中抓取数据

strData = netReader.ReadLine();


//清理它一点点

strData = strData.Trim(new char [3] {''\ a'',''\ r'',''\ n''});


//发送它进行解析

logToScreen(" Received string:" + strData);

ProcessString( strData);

}

catch(exception ex)

{

logToScreen("读取字符串时出错: " + ex.Message.ToString());

}

}

}

catch(异常) exc)

{

logToScreen(" Error Receiving:" + exc.Message.ToString());

}

}


public static string [] Tokenize(string strIncoming)

{

// TODO:定期表达

系统。 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;

}

其他

{

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,


我要做的是让StreamReader循环运行,阅读他们来了(它们会挂在两者之间)。关键是要在另一个线程上运行

StreamReader,这会在收到

消息时引发事件。通过这种方式,您不必担心挂起您的

应用程序,并且可以在消息进入时收到通知。


希望这会有所帮助。

-

- Nicholas Paldino [.NET / C#MVP]

- mv*@spam.guard.caspershouse.com


" JoKur" < Jo*@JoKur.net>在消息中写道

news:58 ********************************** @ microsof t.com ...
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]
- mv*@spam.guard.caspershouse.com

"JoKur" <Jo*@JoKur.net> wrote in message
news:58**********************************@microsof t.com...
你好,

首先让我告诉你,我对C#很新,并且在我学习的同时学习。我正在尝试编写一个客户端应用程序来与服务器进行通信(我没有写过)。来自服务器的每条消息都在一行(最后是\\ n)

形成为[Message] [Optional Argument1] [Optional Argument2] - 每个
其中被一个空间隔开。引号中包含空格的参数
在引文中。

所以,我能够打开与服务器的连接。当我向
发送消息时,它立即响应并使用
streaReader.Readline()解析它。
- 该部分有效。问题是服务器每隔几秒钟也会发送状态消息,这些消息似乎都会丢失。我不知道如何在流中存在数据时引发事件,所以我设置了一个
计时器来轮询流。
我尝试过使用streamReader.Peek()!= null但它挂了,我试过了
streamReader.ReadLine()但它挂了。任何建议都非常感谢。我正在使用Beta 2

代码如下

提前致谢!!
Joe

使用系统;
使用System.ComponentModel;
使用System.Draw;
使用System.Drawing;
使用System.Text;
使用System.Windows.Forms;
使用System .Collections;
使用System.Threading;
使用System.Net.Sockets;
使用System.IO;

公共委托void ConnectionHandler(bool State); <公共委托void ControlChangeHandler(字符串消息);

公共部分类MMConnection:表格
{

// --------- -------------------------------------------------- ---
//类变量
私有的NetworkStream netStream;
私有StreamWriter netWriter;
私有StreamReader netReader;
公共TcpClient netClient;
私有bool netClientStart = false;
private bool netClientConnected = false;
私有System.Net.IPAddress ipAddress =
System.Net.IPAddress.Parse(&qu ot; 127.0.0.1");
private int ipPort = 1632;
private String strUsername =" Contemporary";
private String strPassword =" techspa";
private bool blnLoggedIn = false;

//定义此类可以引发的事件
公共事件ConnectionHandler OnConnectionChanged;
公共事件ControlChangeHandler OnControlChanged;

// - -------------------------------------------------- -----------
//构造函数
公共MMConnection()
{
InitializeComponent();
}

启动客户端
public void ConnectionStart()
{netClientStart = true;
tmrStatus.Enabled = true;
}

public void ConnectionStop()
{
尝试
{logoSoScreen(&关闭连接);

//关闭连接 netWriter.Close();
netReader.Close();
netStream.Close();
netClient.Close();
}
catch(例外e )
{logoSoS creen(关闭连接错误: + e.Message.ToString());
}

私有void StreamWrite(string strMessage)
{
尝试
{
if(strMessage!=" sg")logToScreen(" Sending string:" + strMessage);
netWriter.Write(strMessage +" \\\\ n");
netWriter.Flush();
}
catch(例外e)
{
netClientConnected = false; //无法发送 - 客户端必须已断开连接
Console.WriteLine(发送字符串错误:" + e.Message.ToString());
}
}

public void MessageSend(string strMessage)
{/> StreamWrite(strMessage);
}
//向服务器发送密码
private void sendLogin()
{/> StreamWrite(" li""" + strUsername +"" + strPassword);
}

// Parse来自服务器的响应
private void ProcessString(String strData)
{
int foundPosition; //第一个空格的位置
String firstToken; //第一个令牌(命令或错误

//解析第一个令牌
foundPosition = strData.IndexOf(@"");
if(foundPosition> -1)
{
firstToken = strData.Substring(0,foundPosition).ToString();
}

{
firstToken = strData。 ToString();
}
//执行第一个令牌
开关(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://没有令牌
休息;
}
}

private void tmrStatus_Tick(object sender,EventArgs e)
{
if(netClientConnected)
{
tmrRead.Enabled = true;
StreamWrite(" sg"); //状态获取
}

{
if(netClientStart)
{
尝试
{

netClient = new TcpClient();
//创建TcpClient并连接到服务器
netClient.Connect(ipAddress,ipPort);
//UpdateConnectionIndicator(netClient.Connected); //移动到
登录后
//获取与TcpClient关联的网络流
netStream = netClient.GetStream();
netClientConnected = true;
logToScreen(Connection Successfull to:" + ipAddress +" port:" +
ipPort);

//创建读者和作者
netReader = new StreamReader( netStream);
netWriter = new StreamWriter(netStream);
Console.WriteLine(Got Streams!);
}
catch(异常错误)
{
Console.Write(" Error:" + error.ToString());
netClientConnected = false;
}
}
}

//更新颜色
//UpdateConnectionIndicator(netClient.Connected);
}
私有void logToScreen(String strMessage)
{
lstReceive.Items.Add(strMessage);
Console.WriteLine(strMessage);
}
私有空btnSend_Click(对象发送者,EventArgs e)
{
StreamWrite(txtSend.Text);
}

ivate void tmrRead_Tick(object sender,EventArgs e)
{
String strData;

尝试
//
//从网络流中读取和显示行
//while(netStream.DataAvailable)
// logToScreen(" End of Stream:" + netReader.EndOfStream);
// logToScreen(" Net Reader:" + netReader.ReadLine()。ToString());
// logToScreen(" End of Stream:" + netReader.EndOfStream);
while(netStream.DataAvailable)
{
尝试
//从套接字中获取数据
strData = netReader.ReadLine( );

//清理一下
strData = strData.Trim(new char [3] {''\ a'',''\ r'',' '\ n''}};

//发送它进行解析
logToScreen(" Received string:" + strData);
ProcessString(strData) ;
}
catch(例外情况)
{
logToScreen(" Error reading string:" + ex.Message.ToString());
}
}
}
catch(例外情况)
{/ /> logToScreen(&错误接收:" + exc.Message.ToString());
}

公共静态字符串[] Tokenize(字符串strIncoming)
// TODO:定期表达
System.Text.RegularExpre ssions.Regex regFilter = new
System.Text.RegularExpressions.Regex
(@" \ a | \s" );

返回(regFilter.Split(strIncoming));
}
私有void UpdateConnectionIndicator(bool blnConnected)
{
如果(blnConnected)
{
staStripConnected.Text ="已连接" ;;
staStripConnected.BackColor = System.Drawing.Color.LightGreen;
}
其他 {
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? 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


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 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:
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没有读取所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆