C#模拟TCP/IP通信

服务端

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SocketDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //TCP协议  
            //IP+端口号:ip指明与哪个计算机通信,端口号(一般为4位)指明是哪个应用程序
            IPAddress ipaddress = new IPAddress(new byte[] { 127, 0, 0, 1 });
            EndPoint point = new IPEndPoint(ipaddress, 7788);

            tcpServer.Bind(point);
            tcpServer.Listen(100);

            int i = 0;
            while (i < 5)
            {
                i++;
                Console.WriteLine("");
                Console.WriteLine("开始监听");
                Socket clientSocket = tcpServer.Accept();//暂停当前线程,直到有一个客户端连接过来,之后进行下面的代码
                Console.WriteLine("一个客户端连接过来了");

                string message1 = "hello 欢迎你";
                byte[] data1 = Encoding.ASCII.GetBytes(message1);
                clientSocket.Send(data1);
                Console.WriteLine("向客户端发送了一条数据");

                for (int j = 0; j < 3; j++)
                {
                    byte[] data2 = new byte[8];//创建一个字节数组做容器,去承接客户端发送过来的数据
                    int length = clientSocket.Receive(data2);

                    string msg = byteToHexStr(data2);

                    // string message2 = Encoding.ASCII.GetString(data2, 0, length);//把字节数据转化成 一个字符串
                    Console.WriteLine("接收到了一个从客户端发送过来的消息:" + msg);
                }
            }
            Console.ReadKey();
        }

        ///  
        /// 字节数组转16进制字符串 
        ///  
        ///  
        ///  
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }
    }
}

客户端

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace ClientDemo
{
    class Program
    {
        static Socket ClientSocket;
        static void Main(string[] args)
        {
            String IP = "127.0.0.1";
            int port = 7788;

            IPAddress ip = IPAddress.Parse(IP);  //将IP地址字符串转换成IPAddress实例
            ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议
            IPEndPoint endPoint = new IPEndPoint(ip, port); // 用指定的ip和端口号初始化IPEndPoint实例
            ClientSocket.Connect(endPoint);  //与远程主机建立连接


            Console.WriteLine("开始发送消息");
            string msg = "6C0010FF700CAEFA94C800AA4D444D3246C9";

            byte[] message = StrToHexByte(msg);  //通信时实际发送的是字节数组,所以要将发送消息转换字节
            // byte[] message = Encoding.ASCII.GetBytes("I am Client!!!");  //通信时实际发送的是字节数组,所以要将发送消息转换字节
            ClientSocket.Send(message);
            Console.WriteLine("发送消息为:" + Encoding.ASCII.GetString(message));
            byte[] receive = new byte[1024];
            int length = ClientSocket.Receive(receive);  // length 接收字节数组长度
            Console.WriteLine("接收消息为:" + Encoding.ASCII.GetString(receive));
            ClientSocket.Close();  //关闭连接
        }

        /// 
        /// 将16进制的字符串转为byte[]
        /// 
        /// 
        /// 
        public static byte[] StrToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
    }
}

你可能感兴趣的:(C#)