System.Net.Socket 异步实现

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 using System.Net;
 5 using System.Net.Sockets;
 6 using System.Threading;
 7 using System.IO;
 8 
 9 namespace CSocketServer
10 {
11     public class SocketObject
12     {
13         public Socket CSocket = null;
14         public const int BufferSize = 8;
15         public byte[] Buffer = new byte[BufferSize];
16         public StringBuilder DataBuilder = new StringBuilder();
17     }
18 
19     class Program
20     {
21         static void Main(string[] args)
22         {
23             Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
24 
25             IPEndPoint point = new IPEndPoint(IPAddress.Any, 55000);
26 
27             socket.Bind(point);
28             socket.Listen(100);
29 
30             Console.WriteLine("Waiting For Client Connect...");
31 
32             socket.BeginAccept(new AsyncCallback(AcceptCallBack), socket);
33             Console.Read();
34         }
35 
36         static void AcceptCallBack(IAsyncResult ar)
37         {
38             Socket socket = (Socket)ar.AsyncState;
39             Socket handler = socket.EndAccept(ar);
40             socket.BeginAccept(new AsyncCallback(AcceptCallBack), socket);
41             SocketObject obj = new SocketObject();
42             obj.CSocket = handler;
43             handler.BeginReceive(obj.Buffer, 0, SocketObject.BufferSize, SocketFlags.None,
44                 new AsyncCallback(ReceiveCallBack), obj);
45         }
46 
47         static void ReceiveCallBack(IAsyncResult ar)
48         {
49             SocketObject obj = (SocketObject)ar.AsyncState;
50             Socket socket = obj.CSocket;
51 
52             int bytesRead = socket.EndReceive(ar);
53             string data = string.Empty;
54             if (bytesRead > 0)
55             {
56                 obj.DataBuilder.Append(Encoding.Default.GetString(obj.Buffer, 0, bytesRead));
57 
58                 socket.BeginReceive(obj.Buffer, 0, SocketObject.BufferSize, SocketFlags.None,
59                     new AsyncCallback(ReceiveCallBack), obj);
60             }
61             else
62             {
63                 File.WriteAllText(string.Format(@"D:\{0}.txt", DateTime.Now.ToString("MMddHHmmssfff")), obj.DataBuilder.ToString());
64                // Console.WriteLine(obj.DataBuilder.ToString());
65                 Console.WriteLine("Received {0} Bytes Data...", Encoding.Default.GetBytes(obj.DataBuilder.ToString()).Length);
66             }
67 
68         }
69     }
70 }
posted @ 2012-07-02 17:19  star丶清影  阅读(815)  评论(0编辑  收藏  举报