C#关于TCP的Socket网络连接Demo

服务器端:

防止数据粘包类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    
    
    class Message
    {
    
    
        private byte[] data = new byte[1024];
        private int startIndex = 0; //我们存取了多少个字节的数据都在数组里面

        public void AddCount(int count)
        {
    
    
            startIndex += count;
        }

        public byte[] Data
        {
    
    
            get {
    
     return data; }        
        }

        public int StartIndex
        {
    
    
            get {
    
     return startIndex; }
        }

        
        public int RemainSize
        {
    
     
            //剩余的字节量
            get {
    
     return data.Length - startIndex; }
        }

        /// <summary>
        /// 解析数据或者是叫做读取数据
        /// </summary>
        public void ReadMessage()
        {
    
    
            while (true)
            {
    
    
                if (startIndex <= 4) return;
                int count = BitConverter.ToInt32(data,0);
                if ((startIndex - 4) >= count)
                {
    
    
                    string s = Encoding.UTF8.GetString(data, 4, count);
                    Console.WriteLine("解析出一条数据:" + s);
                    Array.Copy(data, count + 4, data, 0, startIndex - 4 - count);
                    startIndex -= (count + 4);
                }
                else
                {
    
    
                    break;
                }
            }
        }
    }
}

服务器端接受客户端数据处理代码:

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

//服务器端
namespace ConsoleApplication1
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            StartServerAsync();
            Console.ReadKey();
        }

        static void StartServerAsync()
        {
    
    
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //本机IP:192.168.0.109   万能IP:127.0.0.1 此IP在任何电脑上都是指本机的局域网IP
            //IpAddree:IPV4地址       IpEndPoint  IPV4地址:port   也就是IPV4地址加上端口号
            //IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 0, 109 });
            //上面连接IP这种方式不推荐使用,推荐使用下面一种方式
            IPAddress ipAddress = IPAddress.Parse("192.168.0.109");
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 88);
            //绑定IP和端口号
            serverSocket.Bind(ipEndPoint);
            //开始监听端口号
            serverSocket.Listen(0); 



            //接受一个客服端连接
            //Socket clientSocket = serverSocket.Accept();
            //让服务器可以接受多个服务器传递过来的消息
            serverSocket.BeginAccept(AcceptCallBack, serverSocket);          
        }

        static Message msg = new Message(); 
        static void AcceptCallBack(IAsyncResult ar)
        {
    
    
            Socket serverSocket = ar.AsyncState as Socket;
            Socket clientSocket = serverSocket.EndAccept(ar);

            //向客服端发送一条消息
            string msgStr = "Hello client! 你好...";
            //把字符串文本格式转化为字节数组格式
            byte[] data = System.Text.Encoding.UTF8.GetBytes(msgStr);
            clientSocket.Send(data);

            clientSocket.BeginReceive(msg.Data, msg.StartIndex, msg.RemainSize, SocketFlags.None, ReceiveCallBack, clientSocket);

            serverSocket.BeginAccept(AcceptCallBack, serverSocket);
        }
        static byte[] dataBuffer = new byte[1024];
        static void ReceiveCallBack(IAsyncResult ar)
        {
    
    
            Socket clientSocket = null;
            try
            {
    
    
                clientSocket = ar.AsyncState as Socket;
                int count = clientSocket.EndReceive(ar);
                if (count == 0)
                {
    
    
                    //如果从客服端接受到的数据长度为0,也就是客服端正常关闭
                    clientSocket.Close();
                    return;
                }
                msg.AddCount(count);
                //string msg = Encoding.UTF8.GetString(dataBuffer, 0, count);
                //Console.WriteLine("从客服端接收到数据:" + msg);
                msg.ReadMessage();
                //clientSocket.BeginReceive(dataBuffer, 0, 1024, SocketFlags.None, ReceiveCallBack, clientSocket);
                clientSocket.BeginReceive(msg.Data, msg.StartIndex, msg.RemainSize, SocketFlags.None, ReceiveCallBack, clientSocket);
            }
            catch (Exception e)
            {
    
    
                Console.WriteLine(e);
                if (clientSocket != null)
                {
    
    
                    //处理的是客户端强制关闭
                    clientSocket.Close();
                }
            }
            //finally块是不管程序有没出错,都会执行
        }
    }
}

客服端
客服端给服务器端传输的数据最前端加上数据长度限制类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 客服端
{
    
    
    class Message
    {
    
    
        public static byte[] GetBytes(string data)
        {
    
    
            byte[] dataBytes = Encoding.UTF8.GetBytes(data);
            int dataLength = dataBytes.Length;
            byte[] lengthBytes = BitConverter.GetBytes(dataLength);
            byte[] newBytes = lengthBytes.Concat(dataBytes).ToArray();
            return newBytes;
        }
    }
}

客户端发送数据到服务器端

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

namespace 客服端
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(new IPEndPoint(IPAddress.Parse("192.168.0.109"), 88));

            byte[] data = new byte[1024];
            int count = clientSocket.Receive(data);
            string msg = Encoding.UTF8.GetString(data, 0, count);
            Console.Write(msg);

            //while (true) 
            //{ 
            //    string s = Console.ReadLine();
            //    if (s == "c")
            //    {
    
    
            //        //如果按下键盘上的c键就关闭掉客户端
            //        clientSocket.Close();
            //        return;
            //    }
            //    clientSocket.Send(Encoding.UTF8.GetBytes(s));
            //}

            //粘包Demo
            for (int i = 0; i < 100; i++)
            {
    
    
                clientSocket.Send(Message.GetBytes(i.ToString()));
            }

            //分包Demo
//            string s = @"回复我uefhweoifwhfweiofhweefoihfowiehfwfwe富瀚微凤凰网覅欧文符号位ufiwhfowigfwfhieowf腹黑欧文回复我if外婆桥fwioefhwoifehwqfw氛围IE哦回复我饿哦if和我覅偶
//            回复我uefhweoifwhfweiofhweefoihfowiehfwfwe富瀚微凤凰网覅欧文符号位ufiwhfowigfwfhieowf腹黑欧文回复我if外婆桥fwioefhwoifehwqfw氛围IE哦回复我饿哦if和我覅偶
//            回复我uefhweoifwhfweiofhweefoihfowiehfwfwe富瀚微凤凰网覅欧文符号位ufiwhfowigfwfhieowf腹黑欧文回复我if外婆桥fwioefhwoifehwqfw氛围IE哦回复我饿哦if和我覅偶
//            回复我uefhweoifwhfweiofhweefoihfowiehfwfwe富瀚微凤凰网覅欧文符号位ufiwhfowigfwfhieowf腹黑欧文回复我if外婆桥fwioefhwoifehwqfw氛围IE哦回复我饿哦if和我覅偶
//            回复我uefhweoifwhfweiofhweefoihfowiehfwfwe富瀚微凤凰网覅欧文符号位ufiwhfowigfwfhieowf腹黑欧文回复我if外婆桥fwioefhwoifehwqfw氛围IE哦回复我饿哦if和我覅偶
//            回复我uefhweoifwhfweiofhweefoihfowiehfwfwe富瀚微凤凰网覅欧文符号位ufiwhfowigfwfhieowf腹黑欧文回复我if外婆桥fwioefhwoifehwqfw氛围IE哦回复我饿哦if和我覅偶
//            回复我uefhweoifwhfweiofhweefoihfowiehfwfwe富瀚微凤凰网覅欧文符号位ufiwhfowigfwfhieowf腹黑欧文回复我if外婆桥fwioefhwoifehwqfw氛围IE哦回复我饿哦if和我覅偶";

            //clientSocket.Send(Encoding.UTF8.GetBytes(s));

            Console.ReadKey();
            clientSocket.Close();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/jianjianshini/article/details/107033787