C# asynchronous TcpListener

MyConnection.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;

namespace AsyncListener
{
    class MyConnection
    {
        public delegate void HandleMessageEvent(TcpClient client, string message);

        private TcpClient _client;
        private NetworkStream _stream;
        private byte[] _buffer;
        private static int _bufsize = 1024;
        private StringBuilder _msg = new StringBuilder();

        public event HandleMessageEvent MessageArrive = null;

        public MyConnection(TcpClient client)
        {
            _client = client;
            _stream = _client.GetStream();
            _buffer = new byte[_bufsize];
        }

        public void Process()
        {
            _stream.BeginRead(_buffer, 0, _buffer.Length, OnRead, null);
        }

        private void OnRead(IAsyncResult ar)
        {
            int count = _stream.EndRead(ar);
            if (count > 0)
            {
                string value = Encoding.ASCII.GetString(_buffer, 0, count);
                foreach (char ch in value)
                {
                    if (ch == '\n')
                    {
                        if (_msg.Length > 0)
                        {
                            if (_msg[_msg.Length - 1] == '\r') _msg.Remove(_msg.Length - 1, 1);
                            if (MessageArrive != null) MessageArrive(_client, _msg.ToString());
                            _msg.Clear();
                        }
                    }
                    else
                        _msg.Append(ch);
                }
            }
            _stream.BeginRead(_buffer, 0, _buffer.Length, OnRead, null);
        }
    }
}


MyListener.cs

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

namespace AsyncListener
{
    class MyListener
    {
        private TcpListener _server;
        private int _port;
        private Dictionary<string, MyConnection> _clientMap = new Dictionary<string, MyConnection>();

        public event MyConnection.HandleMessageEvent ClientMessageArrive = null;

        public MyListener(int port)
        {
            _port = port;
            _server = new TcpListener(_port);
        }

        public void Start()
        {
            _server.Start();
            _server.BeginAcceptTcpClient(OnAccept, _server);
        }

        private void OnAccept(IAsyncResult ar)
        {
            TcpClient client = _server.EndAcceptTcpClient(ar);
            Console.WriteLine("Accept client from " + client.Client.RemoteEndPoint.ToString());
            MyConnection conn = new MyConnection(client);
            conn.MessageArrive += ClientMessageArrive;

            _clientMap.Add(client.Client.RemoteEndPoint.ToString(), conn);

            conn.Process();

            _server.BeginAcceptTcpClient(OnAccept, _server);
        }

    }
}

Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace AsyncListener
{
    class Program
    {
        static void MsgArrive(TcpClient client, string msg)
        {
            Console.WriteLine("msg {0} from {1}", msg, client.Client.RemoteEndPoint.ToString());
        }

        static void Main(string[] args)
        {
            MyListener listener = new MyListener(12345);
            listener.ClientMessageArrive += MsgArrive;
            listener.Start();
            Console.WriteLine("Listen on port 12345");

            Console.ReadLine();
        }
    }
}









展开阅读全文

没有更多推荐了,返回首页