2017-01-13 19 views
2

C#でネットワーク関連の作業をしていて、クライアント/サーバーモデルの作成が完了したばかりです。私が抱えている唯一の問題は、データを送信しなければならないときに、データの一部が途切れてしまうことです。たとえば、「He​​llo there!」というメッセージを送信し、「Hello」を送信しただけです。TCPクライアント/サーバーのメッセージが正しく送信されない

例:サーバーの

image

私のコード

public static TcpClient tcpcl = new TcpClient(); 
    public static NetworkStream netstream; 
    static void Main(string[] args) 
    { 
     while(!tcpcl.Connected) 
     { 
      try 
      { 
       tcpcl.Connect("127.0.0.1", 1234); 
      } 

      catch 
      { 

      } 
     } 
     netstream = tcpcl.GetStream(); 
     while(tcpcl.Connected) 
     { 
      byte[] buffer = new byte[tcpcl.ReceiveBufferSize]; 
      int unicodeData = netstream.Read(buffer, 0, tcpcl.ReceiveBufferSize); 
      string plainText = Encoding.Unicode.GetString(buffer, 0, unicodeData); 
      Console.WriteLine(plainText); 

     } 

     tcpcl.Close(); 
    } 

クライアントクライアント、変更に

public static TcpListener tcpl = new TcpListener(IPAddress.Any, 1234); 
    public static TcpClient tcpcl; 
    public static NetworkStream netstream; 
    static void Main(string[] args) 
    { 
     tcpl.Start(); 
     Console.WriteLine("Waiting for connection..."); 
     tcpcl = tcpl.AcceptTcpClient(); 
     netstream = tcpcl.GetStream(); 
     Console.WriteLine("Connection Established"); 
     while(tcpcl.Connected) 
     { 
      Console.WriteLine("Enter a message: "); 
      string ptMessage = Console.ReadLine(); 
      netstream.Write(Encoding.Unicode.GetBytes(ptMessage), 0, ptMessage.Length); 
      Console.WriteLine("Sent message"); 
     } 
     tcpcl.Close(); 
    } 

答えて

1

のための私のコード:

string ptMessage = Console.ReadLine(); 
netstream.Write(Encoding.Unicode.GetBytes(ptMessage), 0, ptMessage.Length); 

へ:

string ptMessage = Console.ReadLine(); 
byte[] bytes = Encoding.Unicode.GetBytes(ptMessage); 
netstream.Write(bytes, 0, bytes.Length); 

Write()の最後のパラメータが返されるバイト配列ではなく、元の文字列の長さの長さでなければなりません。

+0

愚かな間違い。ご協力いただきありがとうございます! – rrrrrrrrrrrrrrrr

+0

それが起こります。時々、余分な目を必要とします... –

関連する問題