zoukankan      html  css  js  c++  java
  • Socket Async Receive Data to LinkedList Buffer (telnet proxy server)

    
    namespace Test
    {
        using System;
        using System.Net;
        using System.Net.Sockets;
        using System.Text;
        using Microshaoft;
        public class AsyncSocketAsyncQueueHandlerProxyServer
        {
            public static int Main(String[] args)
            {
                AsyncSocketAsyncQueueHandlerProxyServer x = new AsyncSocketAsyncQueueHandlerProxyServer();
                x.StartListening();
                return 0;
            }
            public void StartListening()
            {
                //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddress;
                IPAddress.TryParse("127.0.0.1", out ipAddress);
                IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 12021);
                Socket listener = new Socket
                                        (
                                            AddressFamily.InterNetwork
                                            , SocketType.Stream
                                            , ProtocolType.Tcp
                                        );
                listener.Bind(localEndPoint);
                Console.WriteLine("Listening ...");
                listener.Listen(10);
                int i = 0;
                while (true)
                {
                    Socket proxySocket = listener.Accept();
                    //socket.Blocking = true;
                    Console.WriteLine("accept");
                    Socket socket = new Socket
                                            (
                                                AddressFamily.InterNetwork
                                                , SocketType.Stream
                                                , ProtocolType.Tcp
                                            );
                    socket.Blocking = true;
                    socket.Connect("bbs.newsmth.net", 23); //连接
                    UserToken token = new UserToken();
                    token.userID = "handler";
                    SocketAsyncDataHandler<UserToken> handler = new SocketAsyncDataHandler<UserToken>(socket, token);
                    handler.ReceiveDataBufferLength = 1;
                    handler.ID = 0;
                    handler.StartReceiveData();
                    UserToken token2 = new UserToken();
                    token2.userID = "proxy";
                    SocketAsyncDataHandler<UserToken> proxyHandler = new SocketAsyncDataHandler<UserToken>(proxySocket, token2);
                    proxyHandler.ReceiveDataBufferLength = 1;
                    proxyHandler.ID = i++;
                    proxyHandler.StartReceiveData();
                    ProxyHandlersPair<UserToken> pair = new ProxyHandlersPair<UserToken>(handler, proxyHandler);
                    pair.DataReceivedProxy += new ProxyHandlersPair<UserToken>.DataReceivedProxyEventHandler(pair_DataReceivedProxy);
                }
            }
            void pair_DataReceivedProxy(SocketAsyncDataHandler<UserToken> source, byte[] data, SocketAsyncDataHandler<UserToken> destination)
            {
                string s = Encoding.GetEncoding("gbk").GetString(data);
                Console.WriteLine("[source: {0}],[destination: {1}],[data: {2}],[length: {3}]", source.Token.userID, destination.Token.userID, s, data.Length);
                destination.SendDataAsync(data);
            }
        }
        public class UserToken
        {
            public string userID;
        }
    }
    namespace Microshaoft
    {
        using System;
        using System.Net.Sockets;
        using System.Text;
        using System.Threading;
        public class ProxyHandlersPair<T>
        {
            private SocketAsyncDataHandler<T> _proxyHandler;
            public SocketAsyncDataHandler<T> ProxyHandler
            {
                get
                {
                    return _proxyHandler;
                }
            }
            private SocketAsyncDataHandler<T> _handler;
            public SocketAsyncDataHandler<T> Handler
            {
                get
                {
                    return _handler;
                }
            }
            public delegate void DataReceivedProxyEventHandler
                                            (
                                                SocketAsyncDataHandler<T> source
                                                , byte[] data
                                                , SocketAsyncDataHandler<T> destination
                                            );
            public event DataReceivedProxyEventHandler DataReceivedProxy;
            public ProxyHandlersPair(SocketAsyncDataHandler<T> proxy, SocketAsyncDataHandler<T> handler)
            {
                _proxyHandler = proxy;
                _handler = handler;
                new Thread
                            (
                                delegate()
                                {
                                    StartProxyReceivedData();
                                }
                            ).Start();
                new Thread
                            (
                                delegate()
                                {
                                    StartReceivedData();
                                }
                            ).Start();
            }
            private void StartProxyReceivedData()
            {
                while (true)
                {
                    
                    int l = 1024;
                    
                    byte[] buffer = new byte[l];
                    int r = _proxyHandler.ReadData(buffer);
                    if (r <= 0)
                    {
                        Thread.Sleep(100);
                        continue;
                    }
                    if (r < l)
                    {
                        Array.Resize<byte>(ref buffer, r);
                    }
                    if (DataReceivedProxy != null)
                    {
                        DataReceivedProxy(_proxyHandler, buffer, _handler);
                    }
                }
            }
            private void StartReceivedData()
            {
                while (true)
                {
                    
                    int l = 1024;
                    
                    byte[] buffer = new byte[l];
                    int r = _handler.ReadData(buffer);
                    if (r <= 0)
                    {
                        Thread.Sleep(100);
                        continue;
                    }
                    if (r < l)
                    {
                        Array.Resize<byte>(ref buffer, r);
                    }
                    if (DataReceivedProxy != null)
                    {
                        DataReceivedProxy(_handler, buffer, _proxyHandler);
                    }
                }
            }
            public void handler_DataReceivedCompletedAsyncProcess(SocketAsyncDataHandler<T> sender, byte[] data)
            {
                if (DataReceivedProxy != null)
                {
                    DataReceivedProxy(sender, data, _proxyHandler);
                }
            }
        }
    }
    namespace Microshaoft
    {
        using System;
        using System.Net.Sockets;
        using System.Collections.Generic;
        public class SocketAsyncDataHandler<T>
        {
            private LinkedList<byte[]> _receivedDataLinkedList = new LinkedList<byte[]>();
            public delegate void DataEventHandler(SocketAsyncDataHandler<T> sender, byte[] data);
            public event DataEventHandler AsyncDataReceivedCompleted;
            private object _syncLockObject = new object();
            private T _token;
            public T Token
            {
                get
                {
                    return _token;
                }
            }
            public SocketAsyncDataHandler(Socket socket, T token)
            {
                _socket = socket;
                _token = token;
            }
            public int ReadData(byte[] buffer)
            {
                int l = buffer.Length;
                int p = 0;
                while (p < l)
                {
                    if (_receivedDataLinkedList.Count <= 0)
                    {
                        break;
                    }
                    if (_receivedDataLinkedList.First == null)
                    {
                        break;
                    }
                    byte[] data = _receivedDataLinkedList.First.Value;
                    int size = ((l - p) > data.Length ? data.Length : (l - p));
                    if ((l - p) >= data.Length)
                    {
                        lock (_syncLockObject)
                        {
                            _receivedDataLinkedList.RemoveFirst();
                        }
                    }
                    Buffer.BlockCopy(data, 0, buffer, p, size);
                    if ((l - p) < data.Length)
                    {
                        byte[] newData = new byte[size];
                        Buffer.BlockCopy(data, data.Length - size, newData, 0, newData.Length);
                        _receivedDataLinkedList.First.Value = newData;
                    }
                    p += size;
                }
                return p;
            }
            private Socket _socket;
            private int _id;
            public int ID
            {
                set
                {
                    _id = value;
                }
                get
                {
                    return _id;
                }
            }
            private int _receiveDataBufferLength = 1024;
            public int ReceiveDataBufferLength
            {
                set
                {
                    _receiveDataBufferLength = value;
                }
            }
            public void SendData(byte[] data)
            {
                _socket.Send(data);
            }
            public void SendDataAsync(byte[] data)
            {
                SocketAsyncEventArgs e = new SocketAsyncEventArgs();
                e.AcceptSocket = _socket;
                e.SetBuffer(data, 0, data.Length);
                _socket.SendAsync(e);
            }
            public void StartReceiveData()
            {
                SocketAsyncEventArgs e = new SocketAsyncEventArgs();
                e.AcceptSocket = _socket;
                e.Completed += new EventHandler<SocketAsyncEventArgs>(ReceivedData_Completed);
                byte[] buffer = new byte[_receiveDataBufferLength];
                e.SetBuffer(buffer, 0, buffer.Length);
                _socket.ReceiveAsync(e);
            }
            private void ReceivedData_Completed(object sender, SocketAsyncEventArgs e)
            {
                int l = e.BytesTransferred;
                if (l > 0)
                {
                    byte[] data = new byte[l];
                    Buffer.BlockCopy(e.Buffer, 0, data, 0, data.Length);
                    lock (_syncLockObject)
                    {
                        _receivedDataLinkedList.AddLast(data);
                    }
                    if (AsyncDataReceivedCompleted != null)
                    {
                        AsyncDataReceivedCompleted(this, data);
                    }
                }
                _socket.ReceiveAsync(e);
            }
        }
    }
    
    
  • 相关阅读:
    POJ 1129 深搜&四色染图&模拟
    POJ 1011 很经典的树枝拼凑的深度搜索
    HDU 2564 词组缩写
    Java中的split函数的用法
    java中next和nextline的区别
    简探this和super
    再探Java中的继承加载顺序
    Java面向接口编程小例子 2
    Dos命令整理集(持续更新)
    VMware WorkStation9.0虚拟机如何运行WINPE
  • 原文地址:https://www.cnblogs.com/Microshaoft/p/1853327.html
Copyright © 2011-2022 走看看