2
C#でネットワーク関連の作業をしていて、クライアント/サーバーモデルの作成が完了したばかりです。私が抱えている唯一の問題は、データを送信しなければならないときに、データの一部が途切れてしまうことです。たとえば、「Hello there!」というメッセージを送信し、「Hello」を送信しただけです。TCPクライアント/サーバーのメッセージが正しく送信されない
例:サーバーの
私のコード
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();
}
愚かな間違い。ご協力いただきありがとうございます! – rrrrrrrrrrrrrrrr
それが起こります。時々、余分な目を必要とします... –