Socket文件传输总结

客户端发送

using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Threading;

private FileStream SentFile;
Socket socket;
Thread mythread;

//选择文件
private void button1_Click(object sender, System.EventArgs e)
{
    if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
        txtFileName.Text = openFileDialog1.FileName;
}

//发送文件大小信息
private void button2_Click(object sender, System.EventArgs e)
{
    string ip = this.txtRemoIP.Text;
    string port = this.txtRemoport.Text;

    IPAddress serverIp = IPAddress.Parse(ip);
    int serverPort = Convert.ToInt32(port);
    IPEndPoint iep = new IPEndPoint(serverIp, serverPort);
    IPHostEntry host = Dns.GetHostByAddress(iep.Address);
    string HostName = host.HostName;

    socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    socket.Connect(iep);

    string filename = this.txtFileName.Text;
    SentFile = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
    int nPos = filename.LastIndexOf("\\");
    if (nPos > -1)
        filename = filename.Substring(nPos + 1);//查找不含路径的文件名
    string fileinfo = "\x01\x53" + SentFile.Length.ToString() + "\x03";

    byte[] byteData = Encoding.ASCII.GetBytes(fileinfo);
    Send(socket, byteData);
}

//发送文件数据 
private void button4_Click(object sender, System.EventArgs e)
{
    string ip = this.txtRemoIP.Text;
    string port = this.txtRemoport.Text;

    IPAddress serverIp = IPAddress.Parse(ip);
    int serverPort = Convert.ToInt32(port);
    IPEndPoint iep = new IPEndPoint(serverIp, serverPort);
    IPHostEntry host = Dns.GetHostByAddress(iep.Address);
    string HostName = host.HostName;

    socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    socket.Connect(iep);

    this.label3.Text = DateTime.Now.ToString();

    long filesize = SentFile.Length;
    byte[] buffer = new byte[filesize];
    int len = SentFile.Read(buffer, 0, buffer.Length);
    Send(socket, buffer);
}

//异步发送
private void Send(Socket handler, byte[] byteData)
{
    // byte[] byteData = Encoding.ASCII.GetBytes(data);             
    handler.BeginSend(byteData, 0, byteData.Length, 0,
         new AsyncCallback(SendCallback), handler);
}

private static void SendCallback(IAsyncResult ar)
{
    try
    {
        Socket handler = (Socket)ar.AsyncState;
        int bytesSent = handler.EndSend(ar);
        handler.Shutdown(SocketShutdown.Both);
        handler.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

服务端接收

public static ManualResetEvent allDone = new ManualResetEvent(false);
private Thread th;
private bool listenerRun = true;
Socket listener;
private const int MAX_SOCKET = 10;
long filesize = 0;
int filerby = 0;
FileStream fs = new FileStream("data.txt", FileMode.Create);

public static IPAddress GetServerIP()
{
    IPHostEntry ieh = Dns.GetHostByName(Dns.GetHostName());
    return ieh.AddressList[0];
}

//侦听方法
private void Listen()
{
    try
    {
        int nPort = int.Parse(this.txtLocalPort.Text);
        IPAddress ServerIp = GetServerIP();
        IPEndPoint iep = new IPEndPoint(ServerIp, nPort);
        listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        listener.Bind(iep);
        listener.Listen(10);
        while (listenerRun)
        {
            allDone.Reset();
            listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
            allDone.WaitOne();
        }
    }
    catch (System.Security.SecurityException)
    {
        MessageBox.Show("防火墙安全错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }
}

//
public void AcceptCallback(IAsyncResult ar)
{
    Socket listener = (Socket)ar.AsyncState;
    Socket client = listener.EndAccept(ar);
    allDone.Set();
    StateObject state = new StateObject();
    state.workSocket = client;

    this.statusBar1.Text = "已经连接!";

    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
         new AsyncCallback(readCallback), state);
}

public void readCallback(IAsyncResult ar)
{
    StateObject state = (StateObject)ar.AsyncState;
    Socket handler = state.workSocket;
    int bytesRead = handler.EndReceive(ar);
    if (bytesRead > 0)
    {
        string strmsg = Encoding.ASCII.GetString(state.buffer, 0, bytesRead);
        if (strmsg.IndexOf("\x01\x53") > -1)//文件大小信息
        {
            int s = strmsg.IndexOf("\x01\x53");
            int e = strmsg.IndexOf("\x03");
            string strsize = strmsg.Substring(s + 2, e - s - 2);
            filesize = long.Parse(strsize);
            this.label1.Text = "该文件大小:" + strsize;
        }
        else//文件数据
        {
            this.label1.Text = "正在接收文件....";
            if ((filerby + bytesRead) >= filesize)
            {
                //接收到完整的信息     
                fs.Write(state.buffer, 0, bytesRead);
                fs.Flush();
                fs.Close();
                this.label1.Text = "接收完毕!" + DateTime.Now.ToString();
            }
            else
            {
                fs.Write(state.buffer, 0, bytesRead);
                filerby += bytesRead;
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                     new AsyncCallback(readCallback), state);
            }
        }
    }
}

private void btnListen_Click(object sender, System.EventArgs e)
{
    th = new Thread(new ThreadStart(Listen));//以Listen过程来初始化线程实例       
    th.Start();//启动此线程 
    this.btnListen.Enabled = false;
}

//异步传递的状态对象
public class StateObject
{
    public Socket workSocket = null;
    public const int BufferSize = 1024;
    public byte[] buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
}
Contributors: FHL