C#通讯编程

作者:sjm2003

转自:http://bbs.csdn.net/topics/240024868


Socket通讯:

C# code ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
public  class  XmlSocket
     {
 
         //异步socket诊听
         // Incoming data from client.从客户端传来的数据
         public  static  string  data =  null ;
 
         // Thread signal.线程 用一个指示是否将初始状态设置为终止的布尔值初始化 ManualResetEvent 类的新实例。
         public  static  ManualResetEvent allDone =  new  ManualResetEvent( false );
         //static void Main(string[] args)
         //{
         //    StartListening();
         //}
 
         public  static  void  StartListening()
         {
             // Data buffer for incoming data. 传入数据缓冲
             byte [] bytes =  new  Byte[1024];
             // Establish the local endpoint for the socket. 建立本地端口
             // The DNS name of the computer
             // running the listener is "host.contoso.com".
 
             IPAddress ipAddress;
             String ipString = ConfigurationManager.AppSettings.Get( "SocketIP" );
             if  (ipString== null  || ipString ==String.Empty)
             {
                 IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                 ipAddress = ipHostInfo.AddressList[0];
             }
             else
             {
                 ipAddress = IPAddress.Parse(ipString);
             }
 
             int  port;
             String portString = ConfigurationManager.AppSettings.Get( "SocketPort" );
             if  (portString== null  || portString==String.Empty)
             {
                 port = 11001;
             }
             else
             {
                 port =  int .Parse(portString);
             }
             IPEndPoint localEndPoint =  new  IPEndPoint(ipAddress, port);
 
             // Create a TCP/IP socket.
             Socket listener =  new  Socket(AddressFamily.InterNetwork,
              SocketType.Stream, ProtocolType.Tcp);
 
             // Bind the socket to the local endpoint and listen for incoming connections.绑定端口和数据
             try
             {
                 listener.Bind(localEndPoint);
                 listener.Listen(100);
 
                 while  ( true )
                 {
                     // Set the event to nonsignaled state.设置无信号状态的事件
                     allDone.Reset();
                     // Start an asynchronous socket to listen for connections.重新 启动异步连接
                     listener.BeginAccept( new  AsyncCallback(AcceptCallback), listener);
                     // Wait until a connection is made before continuing.等待连接创建后继续
                     allDone.WaitOne();
                 }
             }
             catch  (Exception e)
             {
                 //
             }
         }
 
         public  static  void  AcceptCallback(IAsyncResult ar)
         {
             try
             {
                 // Signal the main thread to continue.接受回调方法 该方法的此节向主应用程序线程发出信号,
                 //让它继续处理并建立与客户端的连接
                 allDone.Set();
                 // Get the socket that handles the client request.获取客户端请求句柄
                 Socket listener = (Socket)ar.AsyncState;
                 Socket handler = listener.EndAccept(ar);
                 // Create the state object.
                 StateObject state =  new  StateObject();
                 state.workSocket = handler;
                 handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                  new  AsyncCallback(ReadCallback), state);
             }
             catch  (Exception e)
             {
                 //
             }
         }
 
         /// <summary>
         /// 与接受回调方法一样,读取回调方法也是一个 AsyncCallback 委托。
         /// 该方法将来自客户端套接字的一个或多个字节读入数据缓冲区,然后再次调用 BeginReceive 方法,直到客户端发送的数据完成为止。
         /// 从客户端读取整个消息后,在控制台上显示字符串,并关闭处理与客户端的连接的服务器套接字。
         /// </summary>
         /// <param name="ar">IAsyncResult 委托</param>
         public  static  void  ReadCallback(IAsyncResult ar)
         {
             try
             {
                 String content = String.Empty;
                 // Retrieve the state object and the handler socket创建自定义的状态对象 from the asynchronous state object.
                 StateObject state = (StateObject)ar.AsyncState;
                 Socket handler = state.workSocket; //处理的句柄
                 // Read data from the client socket. 读出
                 int  bytesRead = handler.EndReceive(ar);
                 if  (bytesRead > 0)
                 {
                     //业务代码
                     string  result = DoSomeThing(...);
                     String len = Encoding.UTF8.GetBytes(result).Length.ToString().PadLeft(8,  '0' );
                     log.writeLine(len);
                     Send(len + result, handler);
                 }
             }
             catch  (Exception e)
             {
                 //
             }
 
         }
         private  static  void  Send(String data, Socket handler)
         {
             try
             {
                 // Convert the string data to byte data using UTF8 encoding.
                 byte [] byteData = Encoding.UTF8.GetBytes(data);
                 // Begin sending the data to the remote device.
                 handler.BeginSend(byteData, 0, byteData.Length, 0,
                  new  AsyncCallback(SendCallback), handler);
             }
             catch  (Exception e)
             {
                 //
             }
         }
         /// <summary>
         /// 发送
         /// </summary>
         /// <param name="ar"></param>
         private  static  void  SendCallback(IAsyncResult ar)
         {
             try
             {
                 // Retrieve the socket from the state object.
                 Socket handler = (Socket)ar.AsyncState;
 
                 // Complete sending the data to the remote device.向远端发送数据
                 int  bytesSent = handler.EndSend(ar);
                 StateObject state =  new  StateObject();
                 state.workSocket = handler;
 
                 handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new  AsyncCallback(ReadCallback), state);
                 handler.Shutdown(SocketShutdown.Both);
                 handler.Close();
             }
             catch  (Exception e)
             {
//
             }
         }
 
         public  static  void  StopListening()
         {
             allDone.Close();
             log.close();
         }
 
         /// <summary>
         /// 具体处理业务的方法
         /// </summary>
         /// <returns></returns>
         private  static  string  DoSomething( int  i)
         {
             //具体业务代码,返回需要返回的字符串信息
         }
         /// <summary>
         /// 写日志方法
         /// </summary>
         /// <param name="strLog">写入内容</param>
         public  static  void  WriteLog( string  strLog)
         {
              //写入日志代码
         }
     }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值