服务器端:
Thread recvThread; private void StartReceive() { recvThread = new Thread(new ThreadStart(Recv)); recvThread.IsBackground = false; recvThread.Start(); } Socket listenSocket; private void Recv() { IPEndPoint local = new IPEndPoint(Dns.GetHostByName(Dns.GetHostName()).AddressList[0], 2005); EndPoint localEP = (EndPoint)local; listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //定义Socket并初始化 listenSocket.Bind(localEP); listenSocket.Listen(10); while (true) { Socket socket = listenSocket.Accept(); if (socket.Connected) { //先接收文件名 byte[] fileNameBuffer = new byte[1024]; socket.Receive(fileNameBuffer, 0, fileNameBuffer.Length, SocketFlags.None); string fileName = Encoding.UTF8.GetString(fileNameBuffer); string[] str = fileName.Split(new char[] { '#' }); fileName = str[0]; string pathRecv = "d:\\aaa\\" + fileName; FileStream file = new FileStream(pathRecv, FileMode.OpenOrCreate, FileAccess.Write); //写入文件流 //再接收文件内容 byte[] buffer = new byte[1024]; int bytesRecv; int totalBytes = 0; do { bytesRecv = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None); totalBytes += bytesRecv; file.Write(buffer, 0, bytesRecv); } while (bytesRecv > 0); socket.Close(); file.Close(); } } }
客户端
private void SendFile(string path, string ip, int port) { IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(ip), port); //构造结点 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { socket.Connect(remoteEP); } catch { MessageBox.Show("对方不在"); } if (socket.Connected) { FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read); string fileName = fs.Name; int begin = fileName.LastIndexOf("\\"); fileName = fileName.Substring(fileName.LastIndexOf("\\") + 1, fileName.Length - begin - 1); fileName += "#"; //先把文件名发过去 byte[] fileNameBuffer = new byte[1024]; fileNameBuffer = Encoding.UTF8.GetBytes(fileName); socket.Send(fileNameBuffer, 0, fileNameBuffer.Length, SocketFlags.None); //再把文件内容发过去 byte[] fileBuffer = new byte[1024]; int bytesRead; int totalBytes = 0; try { do { bytesRead = fs.Read(fileBuffer, 0, fileBuffer.Length); socket.Send(fileBuffer, 0, bytesRead, SocketFlags.None); totalBytes += bytesRead; } while (bytesRead > 0); MessageBox.Show("发送完毕"); fs.Close(); socket.Close(); } catch { MessageBox.Show("发送文件错误"); } } }