知行合一

享受过程 漠视结果

导航

tcptrans

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace FuckTrans
{
    public class SocketServer
    {
        private Dictionary<int, Socket> _clientList = new Dictionary<int, Socket>();

        public delegate void ServerEventDele(int clientID);
        public delegate void ReceivedDele(int clientID, byte[] buffer);
        //public ServerEventDele OnClientOnLine;
        //public ServerEventDele OnClientOffLine;
        public ReceivedDele OnReceivedBuffer;

        private string _errorMessage;
        /// <summary>
        /// error message
        /// </summary>
        public string ErrorMessage
        {
            get { return _errorMessage; }
        }

        /// <summary>
        /// init
        /// </summary>
        /// <param name="port">port</param>
        public bool Init(int port)
        {
            try
            {
                Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, port);
                serverSocket.Bind(endPoint);
                serverSocket.Listen(3);

                Thread threadListen = new Thread(new ParameterizedThreadStart(ListenSocket));
                threadListen.IsBackground = true;
                threadListen.Start(serverSocket);

                return true;
            }
            catch (Exception ex)
            {
                _errorMessage = ex.ToString();
                return false;
            }
        }

        private void ListenSocket(object server)
        {
            Socket serverSocket = (Socket)server;
            while (true)
            {
                Socket clientSocket = serverSocket.Accept();

                Thread threadGetMessage = new Thread(new ParameterizedThreadStart(GetMessage));
                threadGetMessage.SetApartmentState(ApartmentState.STA);
                threadGetMessage.IsBackground = true;
                threadGetMessage.Start(clientSocket);

                lock (_clientList)
                {
                    if (!_clientList.ContainsValue(clientSocket))
                    {
                        _clientList.Add(clientSocket.Handle.ToInt32(), clientSocket);
                        //OnClientOnLine(clientSocket.Handle.ToInt32());
                    }
                }
            }
        }

        private void GetMessage(object client)
        {
            Socket clientSocket = (Socket)client;
            int clientId = clientSocket.Handle.ToInt32();
            try
            {
                while (true)
                {
                    byte[] buffer = new byte[1024 * 8];
                    int length = clientSocket.Receive(buffer);
                    if (length > 0)
                    {
                        Array.Resize<byte>(ref buffer, length);

                        byte b = buffer[buffer.Length - 1];
                        if (b != 0xFA && b != 0xFB && b != 0xFF)
                        { 
                        }
                        OnReceivedBuffer(clientId, buffer);
                    }
                }

            }
            catch(Exception ex)
            {
                lock (_clientList)
                {
                    if (_clientList.ContainsValue(clientSocket))
                    {
                        _clientList.Remove(clientSocket.Handle.ToInt32());
                        //OnClientOffLine(clientSocket.Handle.ToInt32());
                    }
                    Thread.CurrentThread.Abort();
                }
            }
        }

        /// <summary>
        /// sent to client
        /// </summary>
        /// <param name="clientId">client id</param>
        /// <param name="buffer">buffer</param>
        /// <returns></returns>
        public bool SendMessage(int clientId, byte[] buffer)
        {
            lock (_clientList)
            {
                try
                {
                    _clientList[clientId].Send(buffer);
                    return true;
                }
                catch (Exception ex)
                {
                    _errorMessage = ex.ToString();
                    return false;
                }
            }
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace FuckTrans
{
    public class SocketClient
    {
        private Socket _clientSocket;
        public delegate void ClientEventDele(byte[] buffer);
        public ClientEventDele OnReceivedBuffer;
        //public ClientEventDele OnConnectionExcept;

        private string _errorMessage;
        /// <summary>
        /// error message
        /// </summary>
        public string ErrorMessage
        {
            get { return _errorMessage; }
        }

        public bool Init(string ip, int port)
        {
            try
            {
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
                _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _clientSocket.Connect(endPoint);

                Thread threadGetMessage = new Thread(new ThreadStart(GetMessage));
                threadGetMessage.IsBackground = true;
                threadGetMessage.Start();
                return true;
            }
            catch (Exception ex)
            {
                _errorMessage = ex.ToString();
                return false;
            }
        }

        private void GetMessage()
        {
            try
            {
                while (true)
                {
                    byte[] buffer = new byte[1024 * 8];
                    int length = _clientSocket.Receive(buffer);
                    if (length > 0)
                    {
                        Array.Resize<byte>(ref buffer, length);
                        OnReceivedBuffer(buffer);
                    }
                }
            }
            catch
            {
                //OnConnectionExcept(null);
                Thread.CurrentThread.Abort();
            }
        }

        public bool SendMessage(byte[] buffer)
        {
            try
            {
                _clientSocket.Send(buffer);
                return true;
            }
            catch (Exception ex)
            {
                _errorMessage = ex.ToString();
                return false;
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace FuckTrans
{
    public class JustTransServer
    {
        public delegate void ReceiveProgressDele(int i);
        public ReceiveProgressDele ReceiveProgress;

        private SocketServer server;
        private FileStream write;
        private string fileName;
        private long fileSize;
        private long writeCount;

        public void Init(int port)
        {
            server = new SocketServer();
            server.OnReceivedBuffer = OnReceived;
            server.Init(port);
        }

        private void OnReceived(int clientID, byte[] buffer)
        {
            if (write != null)
            {
                write.Write(buffer, 0, buffer.Length);

                writeCount += buffer.Length;
                int process = Convert.ToInt32((float)writeCount / (float)fileSize * 100f);
                ReceiveProgress(process);

                if (writeCount >= fileSize)
                {
                    write.Close();
                    MessageBox.Show(string.Format("Receive OK\r\nfile size {0}\r\nreceive size {1}", fileSize, writeCount));
                    write = null;
                    fileName = null;
                    fileSize = 0;
                    writeCount = 0;
                    ReceiveProgress(0);
                }
            }
            else
            {
                string mes = Encoding.Default.GetString(buffer);
                if (mes != null && mes.Contains("|"))
                {
                    fileName = mes.Split('|')[0];
                    fileSize = long.Parse(mes.Split('|')[1]);
                    if (StartWrite())
                        server.SendMessage(clientID, new byte[] { 0xff, 0xff });
                }
            }
        }

        private bool StartWrite()
        {
            string info = string.Format("Do you wanna receive file?\r\nfile name {0}\r\nfile size {1}", fileName, fileSize);
            if (MessageBox.Show(info, "receive file", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
            {
                return false;
            }

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = fileName;
            if (sfd.ShowDialog() == DialogResult.Cancel)
            {
                return false;
            }

            string filePath = sfd.FileName;
            
            DriveInfo di = new DriveInfo(filePath.Substring(0, 1));
            if (di.TotalFreeSpace < fileSize)
            {
                MessageBox.Show("not enough space");
                return false;
            }

            write = new FileStream(filePath , FileMode.Create, FileAccess.Write);
            return true;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace FuckTrans
{
    public class JustTransClient
    {
        public delegate void SendProgressDele(int i);
        public SendProgressDele SendProgress;

        private SocketClient client;
        private FileStream read;
        private long fileSize;
        private long readCount;

        public void Init(string ip, int port, string filePath)
        {
            client = new SocketClient();
            client.OnReceivedBuffer = Receive;
            client.Init(ip, port);

            read = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            fileSize = read.Length;
            string[] tmp = filePath.Split(Convert.ToChar("\\"));
            string fileName = tmp[tmp.Length - 1];

            string info = string.Format("{0}|{1}", fileName, fileSize.ToString());
            byte[] buffer = Encoding.Default.GetBytes(info);
            client.SendMessage(buffer);
        }

        private void Receive(byte[] buffer)
        {
            if (buffer.Length == 2 && buffer[0] == 0xff && buffer[1] == 0xff)
            {
                Thread th = new Thread(new ThreadStart(ReadAndSend));
                th.IsBackground = true;
                th.Start();
            }
        }

        private void ReadAndSend()
        {
            try
            {
                if (read.CanRead)
                {
                    int size = 1024 * 8;
                    while(true)
                    {
                        byte[] buffer = new byte[size];
                        int count = read.Read(buffer, 0, buffer.Length);
                        if (count == 0)
                            break;
                        if (count < buffer.Length)
                            Array.Resize<byte>(ref buffer, count);
                        client.SendMessage(buffer);

                        readCount += count;
                        int progress = Convert.ToInt32((float)readCount / (float)fileSize * 100f);
                        SendProgress(progress);
                    } 

                    read.Close();
                    MessageBox.Show(string.Format("Send OK\r\nfile size {0}\r\nsend size {1}", fileSize, readCount));
                    SendProgress(0);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                read.Close();
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace FuckTrans
{
    public partial class FuckTransForm : Form
    {
        public FuckTransForm()
        {
            InitializeComponent();
        }

        private void FuckTransForm_Load(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "All Files|*.*";
            openFileDialog1.FileName = "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            textBox1.Text = openFileDialog1.FileName;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            JustTransClient client = new JustTransClient();
            client.Init(textBox2.Text, 7890, textBox1.Text);
            client.SendProgress = UpdateProgress;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            JustTransServer server = new JustTransServer();
            server.Init(Convert.ToInt32(textBox3.Text));
            server.ReceiveProgress = UpdateProgress;
            button3.Enabled = false;
            button1.Enabled = false;
            button2.Enabled = false;
        }

        private delegate void UpdateProcessDele(int i);
        private void UpdateProgress(int i)
        {
            if (progressBar1.InvokeRequired)
            {
                progressBar1.BeginInvoke(new UpdateProcessDele(UpdateProgress), new object[] { i });
            }
            else
            {
                progressBar1.Value = i;
            }
        }
    }
}

 

posted on 2012-12-28 18:00  项羽  阅读(352)  评论(0编辑  收藏  举报