using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Net;using System.Net.Sockets;using System.IO;namespace 使用Tcp协议传输文件{ public partial class 发送端 : Form { private TcpClient tcpclient; private FileStream fs; private NetworkStream ns; public 发送端() { InitializeComponent(); } private void btn_Select_Click(object sender, EventArgs e) { OpenFileDialog ofdialog = new OpenFileDialog(); if(ofdialog.ShowDialog()==DialogResult.OK) { label1.Text = ofdialog.FileName; } } private void btn_Send_Click(object sender, EventArgs e) { if(txtBox_IPAddress.Text.Equals("")) { MessageBox.Show("输入IP地址"); return; } if(label1.Text.Equals("文件路径:")) { MessageBox.Show("请选择一个文件"); return; } tcpclient =new TcpClient(); tcpclient.BeginConnect(IPAddress.Parse(txtBox_IPAddress.Text), 8080, new AsyncCallback((IAsyncResult Iar) => { this.tcpclient = (TcpClient)Iar.AsyncState; this.tcpclient.EndConnect(Iar); if (this.tcpclient.Connected) { MessageBox.Show("连接成功,现在开始传输"); try { using (ns = this.tcpclient.GetStream()) { fs = new FileStream(label1.Text, FileMode.Open); byte[] buffer = new byte[1024]; fs.Read(buffer, 0, buffer.Length); int len = fs.Read(buffer, 0, buffer.Length); while (len > 0) { ns.Write(buffer, 0, len); len = fs.Read(buffer, 0, buffer.Length); } fs.Close(); } tcpclient.Close();//关闭连接 ns = null; tcpclient = null;//初始化 } catch (Exception SEND_ERROR) { MessageBox.Show("遇到 " SEND_ERROR.Message "\n 传输失败 "); tcpclient.Close(); tcpclient = null;//初始化 } } }) , tcpclient); } }}
评论