C# socket 客户端(异步通讯)

/*

Client.cs

*/

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

namespace WpfApplication1
{
    public class StateObject
    {
        public Socket workSocket = null;
        public const int BufferSize = 1024;
        public byte[] buffer = new byte[BufferSize];
        public StringBuilder sb = new StringBuilder();
    }
    public class SocketClient
    {
        private int port = 3344;
        private string web = "127.0.0.1";
        private Socket client;

        private ManualResetEvent connectDone = new ManualResetEvent(false);
        private ManualResetEvent sendDone = new ManualResetEvent(false);
        public  ManualResetEvent receiveDone = new ManualResetEvent(false);  //接收到合法数据指示

        public bool connect(string web, int port, int time)
        {
            bool ret = true;
            try
            {
                this.port = port;
                this.web = string.Copy(web);
                if (client != null)
                {
                    //client.Shutdown(SocketShutdown.Both);
                    client.Close();
                }
                IPHostEntry ipHostInfo = Dns.GetHostEntry(web);
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, this.port);
                /*创建、开始连接*/
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
                if (connectDone.WaitOne(5000, false))
                {

                }
                else
                {
                    Debug.WriteLine(" 连接失败");
                    ret = false;
                }
            }
            catch
            {
                Debug.WriteLine("连接服务器错误");
                ret = false;
            }
            return ret;
        }
        private void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                Socket client = (Socket)ar.AsyncState;
                client.EndConnect(ar);
                Debug.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString());
                connectDone.Set();
                Receive(client);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }
        private void Receive(Socket client)
        {
            try
            {
                // Create the state object.
                StateObject state = new StateObject();
                state.workSocket = client;
                // Begin receiving the data from the remote device.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state);
            }
            catch
            {
                Debug.WriteLine("接收错误");
            }
        }
        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {

                StateObject state = (StateObject)ar.AsyncState;
                Socket client = state.workSocket;
                int bytesRead = client.EndReceive(ar);
                if (bytesRead > 0)
                {
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
                    Debug.WriteLine("接收数据:"+Common.ToHexString(state.buffer, bytesRead));
                    receiveDone.Set();
                }
                else
                {
                    Debug.WriteLine("远程服务器断开");
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        public bool close()
        {
            if (client != null)
                client.Close();
            return true;
        }
        /// <summary>
        /// string方式发送数据
        /// </summary>
        /// <param name="client">socket 端口</param>
        /// <param name="data">待发送的数据</param>
        /// <returns></returns>
        public void Send(String data)
        {
            try
            {
                // Convert the string data to byte data using ASCII encoding.
                byte[] byteData = Encoding.ASCII.GetBytes(data);
                Debug.WriteLine("发送数据:" + Common.ToHexString(byteData, byteData.Length));
                client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);
            }
            catch
            {
                Debug.WriteLine(" 1.发送数据失败");
            }
        }
        public void Send(byte[] data, int len)
        {
            try
            {
                Debug.WriteLine("发送数据:" + Common.ToHexString(data, len));
                client.BeginSend(data, 0, len, 0, new AsyncCallback(SendCallback), client);
            }
            catch
            {
                Debug.WriteLine(" 1.发送数据失败");
            }
        }
        public void Send(byte[] data)
        {
            try
            {
                Debug.WriteLine("发送数据:" + Common.ToHexString(data, data.Length));
                client.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), client);
            }
            catch
            {
                Debug.WriteLine(" 1.发送数据失败");
            }
        }
        /// <summary>
        /// 发送回调函数
        /// </summary>
        /// <param name="ar"></param>
        /// <returns></returns>
        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                Socket client = (Socket)ar.AsyncState;
                int bytesSent = client.EndSend(ar);
                sendDone.Set();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }

    }
}

/*

common.cs

*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace WpfApplication1
{
    public class Common
    {
        public static string ToHexString(byte[] bytes) // 0xae00cf => "AE00CF " 
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    strB.Append(bytes[i].ToString("X2"));
                }
                hexString = strB.ToString();
            }
            return hexString;
        }
        /// <summary>
        /// byte to string.eg:{0x01,0x31}->"0131"
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string ToHexString(byte[] bytes, int len) // 0xae00cf => "AE00CF " 
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();
                for (int i = 0; i < len; i++)
                {
                    strB.Append(bytes[i].ToString("X2"));
                }
                hexString = strB.ToString();
            }
            return hexString;
        }
        public static byte[] GetBytes(string hexString)
        {
            string str = hexString.Replace(" ", "");
            try
            {
                int len = str.Length / 2;
                byte[] byteArr = new byte[len];
                for (int i = 0; i < len; i++)
                {
                    string sbStr = str.Substring(i * 2, 2);
                    byteArr[i] = byte.Parse(sbStr, NumberStyles.HexNumber);
                }
                return byteArr;
            }
            catch
            {
                return null;
            }
        }
    }
}

单片机,嵌入式LINUX技术交流群:142282597
原文地址:https://www.cnblogs.com/qiujiahong/p/3139979.html