客户端Socket(异步方式)

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

namespace ClientSocket
{
    public class ClientHandle
    {
        private string ip;
        private int port;
        private Socket clientSocket;
        private byte[] byteBuffer;
        private bool socketState = false;

        /// <summary>
        /// ip
        /// </summary>
        public string IP { get; set; }
        /// <summary>
        /// 端口号
        /// </summary>
        public int Port { get; set; }
        /// <summary>
        /// 客户端socket
        /// </summary>
        public Socket ClientSocket { get; set; }

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="ip">ip地址</param>
        /// <param name="port">端口号</param>
        public ClientHandle(string ip, int port)
        {
            this.ip = ip;
            this.port = port;
        }

        /// <summary>
        /// 开启客户端
        /// </summary>
        /// <param name="clientSocket">客户端的socket</param>
        /// <param name="ip">客户端的ip</param>
        /// <param name="port">端口号</param>
        public void StartClient()
        {
            //创建客户端socket对象
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //创建ip对象
            IPAddress address = IPAddress.Parse(ip);
            //创建端口对象
            IPEndPoint endPoint = new IPEndPoint(address, port);
            //异步方法连接服务端
            clientSocket.BeginConnect(endPoint, new AsyncCallback(ConnectHandler), clientSocket);
            //初始化字节数组
            byteBuffer = new byte[clientSocket.ReceiveBufferSize];
            try
            {
                clientSocket.BeginReceive(byteBuffer, 0, byteBuffer.Length, 0,
                    new AsyncCallback(ReceiveHandler), clientSocket);
            }
            catch (Exception)
            {
                Console.WriteLine("收不到服务端的消息");
            }
        }

        /// <summary>
        /// 处理客户端连接服务器
        /// </summary>
        /// <param name="asyncResult">客户端的socket</param>
        private void ConnectHandler(IAsyncResult asyncResult)
        {
            Socket clientSocket = (Socket)asyncResult.AsyncState;
            if (clientSocket.Connected)
            {
                Console.WriteLine($"客户端{clientSocket.LocalEndPoint.ToString()}连接服务器端成功.");
                socketState = true;
                clientSocket.EndConnect(asyncResult);
            }
            else
            {
                Console.WriteLine("客户端连接服务器端失败.");
            }
        }

        /// <summary>
        /// 接收到服务器端发送过来的消息之后的回调方法.
        /// </summary>
        /// <param name="asyncResult"></param>
        private void ReceiveHandler(IAsyncResult asyncResult)
        {
            Socket clientSocket = (Socket)asyncResult.AsyncState;
            try
            {
                int count = clientSocket.EndReceive(asyncResult);
                if (count == 0)
                {
                    Console.WriteLine("长度为0.");
                    return;
                }
                //转码成字符串.
                string str = Encoding.UTF8.GetString(byteBuffer, 0, count);
                Console.WriteLine(str);
            }
            catch (Exception)
            {
                Console.WriteLine("服务端已关闭");
            }

            //重置字节数组.
            byteBuffer = new byte[clientSocket.ReceiveBufferSize];
            //接收下一条数据.
            try
            {
                clientSocket.BeginReceive(byteBuffer, 0, byteBuffer.Length, 0,
                    new AsyncCallback(ReceiveHandler), clientSocket);
            }
            catch (Exception)
            {
                Console.WriteLine("服务端已关闭");
            }
        }

        /// <summary>
        /// 发送消息至服务端
        /// </summary>
        /// <param name="text">消息内容</param>
        public void SendMsgToServer(string text)
        {
            if (socketState == false) return;
            byte[] message = Encoding.UTF8.GetBytes(text);
            try
            {
                clientSocket.BeginSend(message, 0, message.Length, 0, new AsyncCallback(SendHandler), clientSocket);
            }
            catch (Exception)
            {
                Console.WriteLine("消息发送失败");
            }
        }

        /// <summary>
        /// 消息发送成功之后的回调方法.
        /// </summary>
        /// <param name="asyncResult"></param>
        private static void SendHandler(IAsyncResult asyncResult)
        {
            Socket socket = (Socket)asyncResult.AsyncState;
            int count = socket.EndSend(asyncResult);
            Console.WriteLine("消息发送成功,长度为:" + count);
        }

        /// <summary>
        /// 关闭客户端
        /// </summary>
        /// <param name="socket"></param>
        public void CloseClient()
        {
            socketState = false;
            clientSocket.Close();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;

namespace ClientSocket
{
    internal class Program
    {

        static void Main(string[] args)
        {
            string ip = "127.0.0.1";
            int port = 8885;
            int arrayLength = 1024;

            ClientHandle clientHandle = new ClientHandle(ip, port);
            clientHandle.StartClient();

            while (true)
            {
                string str = Console.ReadLine();
                clientHandle.SendMsgToServer(str);
            }

            Console.ReadKey();
        }

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值