这是客户端程序: C# code public partial class Form1 : Form { TcpClient tcp; IPEndPoint remoteEP; FileStream fs; public Form1() { InitializeComponent(); tcp = new TcpClient(); tcp.Client.ReceiveTimeout = 2000 ; remoteEP = new IPEndPoint(IPAddress.Parse( " 192.168.26.98 " ), 12345 ); } private void button1_Click( object sender, EventArgs e) { if (remoteEP != null ) { tcp.Client.BeginConnect(remoteEP, callback, tcp.Client); } } void callback(IAsyncResult ar) { Socket handler = (Socket)ar.AsyncState; try { handler.EndConnect(ar); } catch (Exception ex) { MessageBoxShow(ex.Message); } try { byte [] bytes = Encoding.UTF8.GetBytes( " Move.txt " ); handler.Send(bytes); } catch (Exception ex) { MessageBoxShow(ex.Message); } try { byte [] receive = new byte [ 1024 ]; int count = 0 ; fs = new FileStream( " d://Move.txt " , FileMode.OpenOrCreate); // fs.Position = 0; while ( true ) { count = handler.Receive(receive); if (count > 0 ) { fs.Write(receive, 0 , count); } else // 注意,如果服务器端文件发送完毕后直接断开连接,则会进入这里。 { fs.Flush(); fs.Close(); handler.Close(); MessageBoxShow( " 连接断开,可能是文件已经传输完毕。 " ); break ; } } } catch (Exception ex) { if (fs != null ) { fs.Flush(); fs.Close(); handler.Close(); } MessageBox.Show(ex.Message); } } void MessageBoxShow( string msg) { if ( this .InvokeRequired) { Action showmsg = () => MessageBox.Show(msg); this .Invoke(showmsg); } else { MessageBox.Show(msg); } } } 另外服务器端程序最好在“MessageBoxShow("发送完毕");”将socket连接关闭,因为我这里文件传完后socket就不使用了,忘了在那上面的代码里添加了。 C# code if (File.Exists(file)) { handler.SendFile(file); handler.Close(); MessageBoxShow( " 发送完毕 " ); }