C#Scoket非同期通信実装(データ送信、データ受信)


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

namespace TCP_Server
{
    class Program
    {
        static byte[] buffer = new byte[1024];
        private static int count = 0;
        static void Main(string[] args)
        {
            WriteLine("server:ready", ConsoleColor.Green); //  

            #region     
            //①      Socket,            TCP Stream Socket(     )
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //②  socket            
            //    :http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.bind.aspx
            socket.Bind(new IPEndPoint(IPAddress.Any, 7788));

            //③    ,             
            //    :http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.listen(v=VS.100).aspx
            socket.Listen(10000);

            //④           
            //    :http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.beginaccept.aspx
            socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
            Console.ReadLine();
            #endregion
        }

        #region        
        /// 
        ///        
        /// 
        /// 
        public static void ClientAccepted(IAsyncResult ar)
        {
            #region
            //     
            count++;
            var socket = ar.AsyncState as Socket;
            //       Socket  ,            
            var client = socket.EndAccept(ar);
            //   IP       
            IPEndPoint clientipe = (IPEndPoint)client.RemoteEndPoint;

            WriteLine(clientipe + " is connected,total connects " + count, ConsoleColor.Yellow);

            //        (                )  
            client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), client);
            //            (  )
            socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
            #endregion
        }
        #endregion

        #region         
        /// 
        ///            
        /// 
        /// 
        public static void ReceiveMessage(IAsyncResult ar)
        {
            int length = 0;
            string message = "";
            var socket = ar.AsyncState as Socket;
            //   IP       
            IPEndPoint clientipe = (IPEndPoint)socket.RemoteEndPoint;
            try
            {
                #region
                //    :http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.endreceive.aspx
                length = socket.EndReceive(ar);
                //        
                message = Encoding.UTF8.GetString(buffer, 0, length);
                //      
                WriteLine(clientipe + " :" + message, ConsoleColor.White);
                //       
                socket.Send(Encoding.UTF8.GetBytes("server received data")); //  Unicode
                //       (           ,             )  
                socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
                #endregion
            }
            catch (Exception ex)
            {
                //     
                count--;
                //    
                WriteLine(clientipe + " is disconnected,total connects " + (count), ConsoleColor.Red);
            }
        }
        #endregion

        #region     
        public static void WriteLine(string str, ConsoleColor color)
        {
            Console.ForegroundColor = color;
            Console.WriteLine("[{0}] {1}", DateTime.Now.ToString("MM-dd HH:mm:ss"), str);
        }
        #endregion
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace TCP_Client
{
    class Program
    {
        static byte[] buffer = new byte[1024];
        static void Main(string[] args)
        {
            try
            {
                //①    Socket
                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //②             
                socket.Connect("127.0.0.1", 7788); //localhost    

                WriteLine("client:connect to server success!", ConsoleColor.White);

                //③                     
                socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);

                //④      ,          
                while (true)
                {
                    var message = Console.ReadLine();
                    var outputBuffer = Encoding.UTF8.GetBytes(message);
                    socket.BeginSend(outputBuffer, 0, outputBuffer.Length, SocketFlags.None, null, null);
                }
            }
            catch (Exception ex)
            {
                WriteLine("client:error " + ex.Message, ConsoleColor.Red);
            }
            finally
            {
                Console.Read();
            }

        }

        #region     
        /// 
        ///     
        /// 
        /// 
        public static void ReceiveMessage(IAsyncResult ar)
        {
            try
            {
                var socket = ar.AsyncState as Socket;

                //    :http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.endreceive.aspx
                var length = socket.EndReceive(ar);
                //        
                var message = Encoding.ASCII.GetString(buffer, 0, length);

                //    
                WriteLine(message, ConsoleColor.White);

                //       (           ,              )
                socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
            }
            catch (Exception ex)
            {
                WriteLine(ex.Message, ConsoleColor.Red);
            }
        }
        #endregion

        #region     
        public static void WriteLine(string str, ConsoleColor color)
        {
            Console.ForegroundColor = color;
            Console.WriteLine("[{0}] {1}", DateTime.Now.ToString("MM-dd HH:mm:ss"), str);
        }
        #endregion
    }
}