使用Socket传送文件!

  1 同事在他负责的项目中想使用Socket传送文件,我就写了一个测试的程序.
  2 为了简单起见,测试里没有用多线程和异步方式.只是能把文件传过去.呵呵.代码如下:
  3 服务器端:
  4 using System;
  5 using System.Drawing;
  6 using System.Collections;
  7 using System.ComponentModel;
  8 using System.Windows.Forms;
  9 using System.Data;
 10 using System.Net.Sockets;
 11 using System.Net;
 12 namespace TransmitFileServer {
 13 
 14     public class Form1 : System.Windows.Forms.Form {
 15         private const string CMDGETFILE="GetTestFile";
 16 
 17         private System.Net.Sockets.TcpListener listener=null;
 18         private System.Windows.Forms.Button btnListen;
 19         private System.Windows.Forms.Label label1;
 20         private System.Windows.Forms.TextBox txtStatus;
 21 
 22         private System.ComponentModel.Container components = null;
 23 
 24         public Form1() {
 25 
 26             InitializeComponent();
 27 
 28             string hostname=Dns.GetHostName();            //获得主机名
 29             IPHostEntry entry=Dns.Resolve(hostname);    //通过主机名得到IP列表
 30             IPEndPoint point=new IPEndPoint(entry.AddressList[0],10000);            //用第0个IP和10000端口实例化IPEndPoint
 31            
 32             listener=new TcpListener(point);                                        //也可以用其它的构造函数
 33         }
 34 
 35         protected override void Dispose( bool disposing ) {
 36             if( disposing ) {
 37                 if (components != null) {
 38                     components.Dispose();
 39                 }
 40             }
 41             base.Dispose( disposing );
 42         }
 43 
 44         #region Windows 窗体设计器生成的代码
 45         /// <summary>
 46         /// 设计器支持所需的方法 - 不要使用代码编辑器修改
 47         /// 此方法的内容。
 48         /// </summary>
 49         private void InitializeComponent() {
 50             this.btnListen = new System.Windows.Forms.Button();
 51             this.label1 = new System.Windows.Forms.Label();
 52             this.txtStatus = new System.Windows.Forms.TextBox();
 53             this.SuspendLayout();
 54             //
 55             // btnListen
 56             //
 57             this.btnListen.Location = new System.Drawing.Point(48159);
 58             this.btnListen.Name = "btnListen";
 59             this.btnListen.Size = new System.Drawing.Size(8832);
 60             this.btnListen.TabIndex = 0;
 61             this.btnListen.Text = "开始侦听";
 62             this.btnListen.Click += new System.EventHandler(this.btnListen_Click);
 63             //
 64             // label1
 65             //
 66             this.label1.AutoSize = true;
 67             this.label1.Location = new System.Drawing.Point(816);
 68             this.label1.Name = "label1";
 69             this.label1.Size = new System.Drawing.Size(3517);
 70             this.label1.TabIndex = 1;
 71             this.label1.Text = "状态:";
 72             //
 73             // txtStatus
 74             //
 75             this.txtStatus.Location = new System.Drawing.Point(5412);
 76             this.txtStatus.Multiline = true;
 77             this.txtStatus.Name = "txtStatus";
 78             this.txtStatus.Size = new System.Drawing.Size(309120);
 79             this.txtStatus.TabIndex = 2;
 80             this.txtStatus.Text = "";
 81             //
 82             // Form1
 83             //
 84             this.AutoScaleBaseSize = new System.Drawing.Size(614);
 85             this.ClientSize = new System.Drawing.Size(384205);
 86             this.Controls.Add(this.txtStatus);
 87             this.Controls.Add(this.label1);
 88             this.Controls.Add(this.btnListen);
 89             this.Name = "Form1";
 90             this.Text = "Server";
 91             this.ResumeLayout(false);
 92 
 93         }
 94         #endregion
 95 
 96 
 97         [STAThread]
 98         static void Main() {
 99             Application.Run(new Form1());
100         }
101 
102         private void btnListen_Click(object sender, System.EventArgs e) {
103             try {
104                 this.txtStatus.Text=string.Format("服务器正监听的IP为:{0},端口为:{1}",
105                     ((IPEndPoint)listener.LocalEndpoint).Address,((IPEndPoint)listener.LocalEndpoint).Port);
106                 this.listener.Start();
107                 System.Net.Sockets.TcpClient client = this.listener.AcceptTcpClient();
108                 System.Net.Sockets.NetworkStream stream = client.GetStream();
109                 while(true) {
110                     while(stream.DataAvailable) {
111                         byte[] buff=new byte[1024];
112                         int len=stream.Read(buff,0,buff.Length);
113                         string cmd=System.Text.Encoding.Unicode.GetString(buff,0,len);
114                         if (cmd==CMDGETFILE) {
115                             System.IO.FileStream fs=System.IO.File.Open("Test.dat",System.IO.FileMode.Open,
116                                 System.IO.FileAccess.Read);
117                             System.IO.BinaryReader br=new System.IO.BinaryReader(fs);
118                             try {
119                                 this.txtStatus.Text="正在传输文件";
120                                 while ((len=br.Read(buff,0,buff.Length))!=0) {
121                                     if(stream.CanWrite) {
122                                         stream.Write(buff,0,len);
123                                     }
124                                 }
125                                 stream.Flush();
126                                 stream.Close();
127                                 this.txtStatus.Text="传输文件完毕!";
128                                 return;
129                             }
130                             catch(Exception ex) {
131                                 this.txtStatus.Text="错误:"+ex.Message;
132                                 return;
133                             }
134                             finally {
135                                 br.Close();
136                             }
137                         }
138                         else {
139                             this.txtStatus.Text="命令字非法!";
140                         }
141                     }
142                 }
143             }
144             catch(Exception ex) {
145                 MessageBox.Show(ex.Message);
146             }
147         }
148     }
149 }
150 
151 
152 客户端:
153 using System;
154 using System.Drawing;
155 using System.Collections;
156 using System.ComponentModel;
157 using System.Windows.Forms;
158 using System.Data;
159 using System.IO;
160 using System.Net.Sockets;
161 using System.Net;
162 namespace GetFileClient {
163 
164     public class Form1 : System.Windows.Forms.Form {
165         private System.Net.Sockets.TcpClient client=null;
166         private const string CMDGETFILE="GetTestFile";
167 
168         private System.Windows.Forms.TextBox txtStatus;
169         private System.Windows.Forms.Label label1;
170         private System.Windows.Forms.Button btnConnect;
171         private System.Windows.Forms.Button btnReceive;
172 
173         private System.ComponentModel.Container components = null;
174 
175         public Form1() {
176 
177             InitializeComponent();
178 
179         }
180 
181         protected override void Dispose( bool disposing ) {
182             if( disposing ) {
183                 if (components != null) {
184                     components.Dispose();
185                 }
186             }
187             base.Dispose( disposing );
188         }
189 
190         #region Windows 窗体设计器生成的代码
191         /// <summary>
192         /// 设计器支持所需的方法 - 不要使用代码编辑器修改
193         /// 此方法的内容。
194         /// </summary>
195         private void InitializeComponent() {
196             this.btnConnect = new System.Windows.Forms.Button();
197             this.btnReceive = new System.Windows.Forms.Button();
198             this.txtStatus = new System.Windows.Forms.TextBox();
199             this.label1 = new System.Windows.Forms.Label();
200             this.SuspendLayout();
201             //
202             // btnConnect
203             //
204             this.btnConnect.Location = new System.Drawing.Point(24104);
205             this.btnConnect.Name = "btnConnect";
206             this.btnConnect.TabIndex = 0;
207             this.btnConnect.Text = "连接";
208             this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);
209             //
210             // btnReceive
211             //
212             this.btnReceive.Location = new System.Drawing.Point(208104);
213             this.btnReceive.Name = "btnReceive";
214             this.btnReceive.TabIndex = 1;
215             this.btnReceive.Text = "接收文件";
216             this.btnReceive.Click += new System.EventHandler(this.btnReceive_Click);
217             //
218             // txtStatus
219             //
220             this.txtStatus.Location = new System.Drawing.Point(5616);
221             this.txtStatus.Multiline = true;
222             this.txtStatus.Name = "txtStatus";
223             this.txtStatus.Size = new System.Drawing.Size(30974);
224             this.txtStatus.TabIndex = 4;
225             this.txtStatus.Text = "";
226             //
227             // label1
228             //
229             this.label1.AutoSize = true;
230             this.label1.Location = new System.Drawing.Point(816);
231             this.label1.Name = "label1";
232             this.label1.Size = new System.Drawing.Size(3517);
233             this.label1.TabIndex = 3;
234             this.label1.Text = "状态:";
235             //
236             // Form1
237             //
238             this.AutoScaleBaseSize = new System.Drawing.Size(614);
239             this.ClientSize = new System.Drawing.Size(376141);
240             this.Controls.Add(this.txtStatus);
241             this.Controls.Add(this.label1);
242             this.Controls.Add(this.btnReceive);
243             this.Controls.Add(this.btnConnect);
244             this.Name = "Form1";
245             this.Text = "客户端";
246             this.ResumeLayout(false);
247 
248         }
249         #endregion
250 
251         [STAThread]
252         static void Main() {
253             Application.Run(new Form1());
254         }
255 
256         private void btnConnect_Click(object sender, System.EventArgs e) {
257             IPAddress ip=IPAddress.Parse("10.0.0.153");
258             IPEndPoint remotepoint=new IPEndPoint(ip,10000);
259             client=new TcpClient();
260             try {
261                 client.Connect(remotepoint);
262                 this.txtStatus.Text="连接成功!";
263             }
264             catch(Exception ex) {
265                 this.txtStatus.Text="错误:"+ex.Message;
266                 client=null;
267             }
268         }
269 
270         private void btnReceive_Click(object sender, System.EventArgs e) {
271             if(client==null) {
272                 MessageBox.Show("先连接服务器!");
273                 return;
274             }
275             NetworkStream stream=client.GetStream();
276             string cmd=CMDGETFILE;
277             byte[] bytcmd=System.Text.Encoding.Unicode.GetBytes(cmd);
278             try {
279                 if (stream.CanWrite) {
280                     this.txtStatus.Text="发送命令!";
281                     stream.Write(bytcmd,0,bytcmd.Length);
282                     while(true) {
283                         if(stream.DataAvailable) {
284                             if(stream.CanRead) {
285                                 FileStream fs=File.Open("Test.dat",FileMode.OpenOrCreate,FileAccess.Write);
286                                 BinaryWriter bw=new BinaryWriter(fs);
287                                 try {
288                                     this.txtStatus.Text="正在接收文件";
289                                     byte[] buff=new byte[1024];
290                                     int len=0;
291                                     while((len=stream.Read(buff,0,buff.Length))!=0) {
292                                         bw.Write(buff,0,len);
293                                         bw.Flush();
294                                     }
295                                
296                                     this.txtStatus.Text="接收完毕!";
297                                     return;
298                                 }
299                                 catch(Exception ex) {
300                                     this.txtStatus.Text="错误:"+ex.Message;
301                                     return;
302                                 }
303                                 finally {
304                                     bw.Close();
305                                 }
306                             }
307                         }
308                     }
309                 }
310             }
311             catch(Exception ex) {
312                 MessageBox.Show(ex.Message);
313             }
314         }
315     }
316 }
317 
318 
319 由于小弟对这个也是一知半解,所以也就不做注解说明了,以免贻笑大方贻笑大方,呵呵.
posted @ 2006-08-08 16:30  吴东雷  阅读(1415)  评论(0编辑  收藏  举报