我刚接触C#中与网络相关的事情,刚刚创建了客户端/服务器模型。我遇到的唯一问题是,当我发送数据时,部分内容会被切断。例如,我发送消息"你好!",它刚刚发送"你好"。
示例:
我的服务器代码
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();
}
答案 0 :(得分:2)
在您的客户端,更改:
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()
的最后一个参数应该是返回的字节数组的长度,而不是原始字符串的长度。