socket通信传输的字节是什么内容,客户端和服务端要知道这个字节是文件,是字符串还是其他?应该设计一个协定。例如在内容字节前面插入一个字节表示内容形式,0代表字符串,1代表文件......
private void button1_Click(object sender, EventArgs e) { Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Parse("192.169.11.87"); IPEndPoint endPoint = new IPEndPoint(ip, 5000); socket.Connect(endPoint); string msg = "消息来了"; byte[] buffer = Encoding.UTF8.GetBytes(msg); //如何在buffer前面加一个字节呢,可以使用集合 List<byte> bufferList = new List<byte>(); bufferList.Add(0); bufferList.AddRange(buffer); byte[] newBuffer = bufferList.ToArray(); socket.Send(newBuffer); }
private void button1_Click(object sender, EventArgs e) { Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Parse("192.169.11.87"); IPEndPoint endPoint = new IPEndPoint(ip, 5000); socket.Connect(endPoint); string path = string.Empty; using (FileStream fsRead = new FileStream(path, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[1024 * 1024 * 5]; int r = fsRead.Read(buffer, 0, buffer.Length); List<byte> newBuffer = new List<byte>(); newBuffer.Add(1); newBuffer.AddRange(buffer); // 是r+1 socket.Send(newBuffer.ToArray(), 0, r+1, SocketFlags.None); } }