C#の - StreamReader.ReadLineが正常に動作しません!
-
11-09-2019 - |
質問
単純に私はJavaで何BufferedStreamReader
実装しようとしてきました。私は、オープンソケットストリームを持っているだけで行指向の方法でそれを読みたい - 行ずつ
私は、次のサーバーのコードを持っています。
while (continueProcess)
{
try
{
StreamReader reader = new StreamReader(Socket.GetStream(), Encoding.UTF8);
string command = reader.ReadLine();
if (command == null)
break;
OnClientExecute(command);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
そして、次のクライアントのコード:
TcpClient tcpClient = new TcpClient();
try
{
tcpClient.Connect("localhost", serverPort);
StreamWriter writer = new StreamWriter(tcpClient.GetStream(), Encoding.UTF8);
writer.AutoFlush = true;
writer.WriteLine("login>user,pass");
writer.WriteLine("print>param1,param2,param3");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
tcpClient.Close();
}
サーバーは、非常に最初の行(login>user,pass
)を読み込み、nullを返しますReadLine
!
これは、JavaのBufferedStreamReader
であるように、この行指向のリーダーを達成するための最も簡単な方法は何ですか? :S
解決
典型的なラインリーダーのようなものです
using(StreamReader reader = new StreamReader(Socket.GetStream(), Encoding.UTF8)) {
string line;
while((line = reader.ReadLine()) != null) {
// do something with line
}
}
(私たちは、エラー、およびループを取得した場合でも、我々はそれをusing
確保するためにDispose()
に注意してください)。
あなたがしたい場合は、あなたでし抽象イテレータブロックと、この(関心事の分離):
static IEnumerable<string> ReadLines(Stream source, Encoding encoding) {
using(StreamReader reader = new StreamReader(source, encoding)) {
string line;
while((line = reader.ReadLine()) != null) {
yield return line;
}
}
}
(注意、我々は機能にこれを移動し、イテレータ(レイジー繰り返し、非バッファリングステートマシン)
を作成する「降伏リターン」、で置き換え、「何かをする」を削除しました私たちは、その後、単にとして、これを消費することになります
foreach(string line in ReadLines(Socket.GetStream(), Encoding.UTF8)) {
// do something with line
}
今私達の処理コードはの方法の行を読み取ることを心配する必要はありません - 単に<全角> の行のシーケンス与え、彼らと何かを
。 using
(Dispose()
が)あまりにもTcpClient
に適用されることに注意してください。あなたはIDisposable
をチェックする習慣を作るべきです。例えば(まだあなたのエラー・ログを含む):
using(TcpClient tcpClient = new TcpClient()) {
try {
tcpClient.Connect("localhost", serverPort);
StreamWriter writer = new StreamWriter(tcpClient.GetStream(), Encoding.UTF8);
writer.AutoFlush = true;
writer.WriteLine("login>user,pass");
writer.WriteLine("print>param1,param2,param3");
} catch (Exception ex) {
Console.Error.WriteLine(ex.ToString());
}
}
他のヒント
サーバーのコードにいる間は、接続ごとに1行を読み込むための設定です。あなたは、送信されているすべてのラインを読むことを試み内の別しばらく必要があります。私はそのストリームは、クライアント側で設定されると、すべてのデータを送信するために起こっていると思います。そして、サーバ側で、あなたの流れが効果的にのみ、特定のストリームから1行を読んでます。
このを試してみましたが、得ました
型または名前空間名「流れ」が見つかりませんでした(あなたがusingディレクティブまたはアセンブリ参照が不足しています?) 型または名前空間名「のStreamReader」が見つかりませんでした(あなたがusingディレクティブまたはアセンブリ参照が不足しています?) 型または名前空間名「のStreamReader」が見つかりませんでした(あなたがusingディレクティブまたはアセンブリ参照が不足しています?) 「System.Net.Sockets.Socketは」「GETSTREAM」
の定義が含まれていません。 public string READS()
{
byte[] buf = new byte[CLI.Available];//set buffer
CLI.Receive(buf);//read bytes from stream
string line = UTF8Encoding.UTF8.GetString(buf);//get string from bytes
return line;//return string from bytes
}
public void WRITES(string text)
{
byte[] buf = UTF8Encoding.UTF8.GetBytes(text);//get bytes of text
CLI.Send(buf);//send bytes
}
CLIはソケットです。 いくつかの再ゾーニングするためにれるtcpClientクラスは、右のいずれかのより多くの私のPC上で動作しません、 しかし、Socketクラスだけで正常に動作します。
UTF-8は、本鎖のStreamReader /ライター・エンコーディングです。