//服务端
Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
EndPoint point = new IPEndPoint(IPAddress.Parse("127.21.24.35"), 1324);
soc.Bind(point);
soc.Listen(2);//最大连接数
Console.WriteLine("等待客户端连接");
Socket tcp = soc.Accept();
Console.WriteLine("客户端已连接");
Console.WriteLine(tcp.RemoteEndPoint.ToString());
byte[] data = new byte[1024];
int length = tcp.Receive(data);
string str = Encoding.UTF8.GetString(data);
Console.WriteLine("接收的数据为:" + str);
Console.ReadKey();
//客户端
Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
EndPoint ed = new IPEndPoint(IPAddress.Parse("127.21.24.35"), 1324);
soc.Connect(ed);
byte[] data = Encoding.UTF8.GetBytes("难啊是整的难啊");
soc.Send(data);
Console.ReadKey();
``
`
C#socket黑窗口发送消息,接收后会出现很多a
因为tcp发送的是一个数据包,而你实际的字符串长度不足,所以后面的内容是随机的,可以在发送的数据的开头,加上一个表示长度的整数,后面跟着字符串。
读取的时候,先读取长度,再据此切割数组,再getstring