你是不是对异步Socket 很迷惑? 看完本文的一小类 你就知道大体该做什么,怎么做了....

直接上代码,看完代码你就什么都明白了。

 1     public class Socketer
2 {
3 /// <summary>
4 /// Server
5 /// </summary>
6 /// <param name="serverport">ServerPort</param>
7 public Socketer(int serverport)
8 {
9 Initilize_Bind(serverport);
10 Socket_host.Listen(1);
11 Socket_host.BeginAccept(ar =>
12 {
//这里要注意我这里上面只监听了一个连接,而下面这句也只是简答地吧原来的Socket给覆盖了,如果你要改成多客户端的话需要增加一个列表,
// 并且对列表中的Socket对象分别进行相应的操作
13 Socket_host = Socket_host.EndAccept(ar);
14 Recive();
15 }, null);
16 }
17
18
19
20 //IPAddress _HostIP;
21
22 //public IPAddress HostIP { get { return _HostIP; } }
23
24 /// <summary>
25 /// Client
26 /// </summary>
27 /// <param name="clientport">ClientPort</param>
28 /// <param name="serverport">ServerPort</param>
29 public Socketer(int clientport, int serverport)
30 {
31 Initilize_Bind(clientport);
32 Socket_host.BeginConnect(new IPEndPoint(IPAddress.Loopback, serverport), ar =>
33 {
34 Socket_host.EndConnect(ar);
Recive();
35 }, null);
36 }
37
38 private void Initilize_Bind(int hostport)
39 {
40 Socket_host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
41 //_HostIP = ;
42 Socket_host.Bind(new IPEndPoint(IPAddress.Any, hostport));
43 }
44
45
46
47 public Socket Socket_host;
48 //public List<Socket> Clients = new List<Socket>();
49
50
51 private byte[] Buffer_Recive = new byte[256];
52
53 public virtual void Recive()
54 {
55 if (Socket_host.Connected)
56 {
57 Array.Clear(Buffer_Recive, 0, Buffer_Recive.Length);
58 Socket_host.BeginReceive(Buffer_Recive, 0, Buffer_Recive.Length, SocketFlags.None, ar =>
59 {
60 int getsize= Socket_host.EndReceive(ar);
61 if (GetMsg != null)
62 {
63 //GetMsg.Invoke(Encoding.UTF8.GetString(Buffer_Recive, 0, getsize));
64 //GetMsg.Method.Invoke(null, new object[]{ Encoding.UTF8.GetString(Buffer_Recive, 0, getsize)});
65 GetMsg(Encoding.UTF8.GetString(Buffer_Recive, 0, getsize));
66 //GetMsg.BeginInvoke(,null,null);
67 }
68 Recive();
69 }, null);
70 }
71 }
72
73 public event GetResult GetMsg;
74
75
76 public virtual void Send(string msg)
77 {
78 if (Socket_host.Connected)
79 {
80 byte[] sendbuffer = Encoding.UTF8.GetBytes(msg);
81 Socket_host.BeginSend(sendbuffer, 0, sendbuffer.Length, SocketFlags.None, ar =>
82 {
83 Socket_host.EndSend(ar);
84 }, null);
85 }
86 }
87
88 }
89
90
91 public delegate void GetResult(string msg);
//小菜

//小菜

posted @ 2012-04-08 15:23  SoarNo1  阅读(376)  评论(0编辑  收藏  举报