C#通讯编程(整理)
Socket通讯:
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 \
IPAddress ipAddress;
String ipString = ConfigurationManager.AppSettings.Get(\); 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(\); if (portString==null || portString==String.Empty)
1 / 39
{
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;
2 / 39
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) { // } }
///
/// 与接受回调方法一样,读取回调方法也是一个 AsyncCallback 委托。
/// 该方法将来自客户端套接字的一个或多个字节读入数据缓冲区,然后再次调用 BeginReceive 方法,直到客户端发送的数据完成为止。
/// 从客户端读取整个消息后,在控制台上显示字符串,并关闭处理与客户端的连接的服务器套接字。 ///
/// 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) { // }
3 / 39
}
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) { // } }
///
///
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,newAsyncCallback(ReadCallback), state);
handler.Shutdown(SocketShutdown.Both); handler.Close(); }
catch (Exception e) { //
} }
4 / 39
public static void StopListening() {
allDone.Close(); log.close(); }
///
/// 具体处理业务的方法 ///
///
private static string DoSomething(int i) {
//具体业务代码,返回需要返回的字符串信息 }
///
/// public static void WriteLog(string strLog) {
//写入日志代码 } }
/// 线程执行体,转发消息 ///
/// private void ThreadFunc(object obj) {
//通过转发表得到当前用户套接字
Socket clientSkt = _transmit_tb[obj] as Socket; //主循环 while (true) { try
{ //接受第一个数据包。
//由于程序逻辑结构简单,所以在这里对客户机发送的第一个包内容作逐一判断, //这里的实现不够优雅,但不失为此简单模型的一个解决之道。 byte[] packetBuff = new byte[_maxPacket]; clientSkt.Receive(packetBuff);
string _str = Encoding.Unicode.GetString(packetBuff).TrimEnd('\\0');
5 / 39