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

本文详细介绍了使用Socket进行网络通信的实现过程,包括连接服务器、数据接收与发送的方法,以及如何关闭连接。通过实例展示了从创建Socket到完成数据交互的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*

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;
            }
        }
    }
}

转载于:https://www.cnblogs.com/qiujiahong/p/3139979.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值