伺服器端:
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("傳送檔案錯誤"); } } }