• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

/*

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("\r\n连接失败");
                    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("\r\n1.发送数据失败");
            }
        }
        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("\r\n1.发送数据失败");
            }
        }
        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("\r\n1.发送数据失败");
            }
        }
        /// <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;
            }
        }
    }
}


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
[C#菜鸟]C#Hook(三)Windows常用消息大全发布时间:2022-07-18
下一篇:
C#得到磁盘信息发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap