Socket-传送文件
客户端:
public partial class Form1 : Form { Socket myClientSocket; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { button1.Text = "发送"; } private void button1_Click(object sender, EventArgs e) { myClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("xxxxx"), 49392); myClientSocket.Connect(ipEndPoint); FileStream fileStream = new FileStream(@"C:\Users\Alex\Desktop\test.exe", FileMode.Open); byte[] mybyte = new byte[fileStream.Length]; fileStream.Read(mybyte, 0, mybyte.Length); fileStream.Close(); myClientSocket.Send(mybyte); } }
服务器端
public partial class Form1 : Form { Socket listenServerSocket; Socket socket; public Form1() { InitializeComponent(); listenServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listenServerSocket.Bind(new IPEndPoint(IPAddress.Parse("1xxxx"), 49392)); listenServerSocket.Listen(10); listenServerSocket.BeginAccept(new AsyncCallback(OnConnectRequest), listenServerSocket); } public void OnConnectRequest(IAsyncResult ar) { Socket server1 = (Socket)ar.AsyncState; socket = server1.EndAccept(ar); Byte[] byteDateLine = new byte[10]; server1.BeginAccept(new AsyncCallback(OnConnectRequest), server1); while (true) { int recv = 0; FileStream fs = new FileStream(@"C:\Users\Alex\Desktop\test1.exe", FileMode.Create); while ((recv = socket.Receive(byteDateLine)) > -1) { fs.Write(byteDateLine, 0, recv); } fs.Flush(); fs.Close(); } } }