Example #1
0
        /// <summary>
        /// 收到connect
        /// </summary>
        /// <param name="ar"></param>
        private static void on_local_connected(IAsyncResult ar)
        {
            object[]  ar_arr   = ar.AsyncState as object[];
            Socket    sock_svr = ar_arr[0] as Socket;
            work_item work     = (work_item)ar_arr[1];


            ++_state_dic[work._id]._connect_cnt;
            Socket sock_cli = sock_svr.EndAccept(ar);

            sock_svr.BeginAccept(on_local_connected, ar.AsyncState);
            Socket sock_cli_remote = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                sock_cli_remote.Connect(work._ip_out_host, work._ip_out_port);
            }
            catch (Exception)
            {
                try
                {
                    sock_cli.Shutdown(SocketShutdown.Both);
                    sock_cli_remote.Shutdown(SocketShutdown.Both);
                    sock_cli.Close();
                    sock_cli_remote.Close();
                }
                catch (Exception)
                { }
                --_state_dic[work._id]._connect_cnt;
                return;
            }
            //线程: 接受本地数据 转发至远程
            Thread t_send = new Thread(recv_and_send_caller)
            {
                IsBackground = true
            };
            //线程: 接受远程数据 转发至本地connect 端
            Thread t_recv = new Thread(recv_and_send_caller)
            {
                IsBackground = true
            };

            t_send.Start(new object[] { sock_cli, sock_cli_remote, work._id, true });
            t_recv.Start(new object[] { sock_cli_remote, sock_cli, work._id, false });
            //线程同步
            t_send.Join();
            t_recv.Join();
            //已断开, 连接数-1
            --_state_dic[work._id]._connect_cnt;
        }
Example #2
0
        /// <summary>
        /// 启动映射器
        /// </summary>
        /// <param name="work"></param>
        private static void map_start(work_item work)
        {
            Socket sock_svr    = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            bool   start_error = false;

            try
            {
                sock_svr.Bind(work._ip_in);                                                //绑定本机ip
                sock_svr.Listen(10);
                sock_svr.BeginAccept(on_local_connected, new object[] { sock_svr, work }); //接受connect
            }
            catch (Exception)
            {
                start_error = true;
            }
            finally
            {
                _state_dic.Add(work._id, new state(work._ip_in.ToString(), work._ip_out_host + ":" + work._ip_out_port, !start_error, 0, 0, 0));
            }
        }