IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> C#网络编程TCP的一些代码例子 -> 正文阅读

[网络协议]C#网络编程TCP的一些代码例子

记录自己的学习过程

	最近发现自己学的东西很杂,在各个文件夹下,找起来麻烦又很乱,每次参考一下以前练习的代码,都要打开很多个VS,所以利用下CSDN这个平台,做点笔记。

网络编程基础

服务器客户机
socket()socket()
bind()
listen()
accept()connect()
recv()send()
send()recv()
close()close()

代码

IPAddress类

方法字段
Equals比较两个IP地址AnyAny 用于代表本地系统可用的任何IP
GetHashCodeBroadcast代表本地网络的IP广播地址
GetTypeLoopback回送
HostToNetworkorderNone用于代表系统上没有任何网络接口
IsLoopBack是否是回送地址?
Parse把一个字符串转换成IPAddress
ToString
class IPAdress_test
    {
        /*
         * IP地址类
         */
        public void IPAdress_testRun()
        {
            /*IPAddress类表示一个IP地址*/
            //IPAddress test1 = IPAddress.Parse("192.168.1.1");
            //Parse方法可以将类似"1.1.1.1"此类的字符串转换成ip地址
            IPAddress test6 = IPAddress.Parse("111.111.111.111");   
            IPAddress test2 = IPAddress.Loopback;
            IPAddress test3 = IPAddress.Broadcast;
            IPAddress test4 = IPAddress.Any;
            IPAddress test5 = IPAddress.None;

            //获取主机名字
            IPHostEntry ihe = Dns.GetHostByName(Dns.GetHostName());
            IPAddress myself = ihe.AddressList[0];
            IPAddress myself2 = ihe.AddressList[1];
            if (IPAddress.IsLoopback(test2))
                Console.WriteLine("回送地址(loopback)是{0}", test2.ToString());
            else
                Console.WriteLine("获取回送地址发生错误!");
            Console.WriteLine("本地IP地址是 {0}", myself.ToString());

            if (myself == test2)
                Console.WriteLine("回送地址和本地IP地址相同!");
            else
                Console.WriteLine("回送地址和本地IP地址不同!");

            //Console.WriteLine("The test address is:{0}", test1.ToString());
            Console.WriteLine("The test address is:{0}", test2.ToString());
            Console.WriteLine("The test address is:{0}", test3.ToString());
            Console.WriteLine("The test address is:{0}", test4.ToString());
            Console.WriteLine("The test address is:{0}", test5.ToString());
            Console.WriteLine("The test address is:{0}", test6.ToString());
            Console.WriteLine("The myself2 address is:{0}", myself2.ToString());
        }
    }

IPEndPoint类

方法属性
Create从一个socketAssress创建EndPointAddressIP地址
Equals比较两个AddressFamilyIP系列地址
GetHashCode从IPEndPoint返回散列值Port端口号
GetType返回IPEndPoint实例类型MaxPort
Serialize创建实例的SocketAddressMinPort端口号最小值
ToString
class IPEndPoint_test
    {
        /*
         * IPEndPoint类
         */
        public void IPEndPoint_testRun()
        {
            IPAddress test1 = IPAddress.Parse("111.111.111.111");
            IPEndPoint ie = new IPEndPoint(test1, 8000);

            Console.WriteLine("The IPEndPoint is: {0}", ie.ToString());
            Console.WriteLine("The AddressFamily is: {0}", ie.AddressFamily);
            Console.WriteLine("地址是:{0}", "端口是:{1}",ie.Address, ie.Port);
            Console.WriteLine("端口最小值:{0}", IPEndPoint.MinPort);
            Console.WriteLine("端口最大值:{0}", IPEndPoint.MaxPort);
            ie.Port = 80;
            Console.WriteLine("The changed IPEndPoint value is {0}", ie.ToString());

            SocketAddress sa = ie.Serialize();
            Console.WriteLine("套接字地址是:{0}", sa.ToString());

        }

    }

简单TCP服务器测试

class SimpleTcpServer
    {
        /*
         * 简单TCP服务器测试
         */
        public void SimpleTcpServer_Run()
        {
            int recv;
            byte[] data = new byte[1024];

            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
            Socket newSock = new Socket(AddressFamily.InterNetwork, 
                SocketType.Stream, ProtocolType.Tcp);

            newSock.Bind(ipep);
            newSock.Listen(10);
            Console.WriteLine("等待连接...");

            Socket Client1 = newSock.Accept();
            IPEndPoint Client_ep1 = (IPEndPoint)Client1.RemoteEndPoint;
            Console.WriteLine("已经连接到{0},对方端口{1}", 
                Client_ep1.Address, Client_ep1.Port);

            string welcome = "欢迎连接到我的测试服务器!";
            data = Encoding.UTF8.GetBytes(welcome);

            Client1.Send(data, data.Length, SocketFlags.None);  //往客户端发送数据

            while(true)
            {
                data = new byte[1024];
                recv = Client1.Receive(data);
                if (recv == 0)
                    break;
                Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));
                Client1.Send(data, recv, SocketFlags.None);
            }

            Console.WriteLine("关闭来自{0}的连接!", Client_ep1.Address);

            Client1.Close();
            newSock.Close();

        }
    }

简单TCP客户端测试

class SimpleTcpClient
    {
        /*
         * 简单TCP客户端测试
         */
        public void SimpleTcpClient_Run()
        {
            byte[] data = new byte[1024];
            string input, stringData;

            IPEndPoint ipep = new IPEndPoint(
                IPAddress.Parse("192.168.137.30"), 9050);
            Socket server1 = new Socket(AddressFamily.InterNetwork, 
                SocketType.Stream, ProtocolType.Tcp);

            try
            {
                server1.Connect(ipep);
                if (server1 != null)
                    if (server1.RemoteEndPoint != null)
                        Console.WriteLine("连接成功!\n远程主机地址为{0}",
                            server1.RemoteEndPoint);
                    else
                        Console.WriteLine("找不到服务器!");
            }
            catch(SocketException e)
            {
                Console.WriteLine("无法连接到服务器!");
                Console.WriteLine(e.ToString());
                return;
            }

            int recv = server1.Receive(data);       //返回接收到数据的字节数number
            stringData = Encoding.ASCII.GetString(data, 0, recv);
            Console.WriteLine(stringData);

            while(true)
            {
                input = Console.ReadLine();
                if (input == "exit")
                    break;
                server1.Send(Encoding.ASCII.GetBytes(input));

                data = new byte[1024];
                recv = server1.Receive(data);

                stringData = Encoding.ASCII.GetString(data, 0, recv);
                Console.WriteLine(stringData);
            }

            Console.WriteLine("断开与服务器的连接!");
            server1.Shutdown(SocketShutdown.Both);
            server1.Close();

        }
    }

指定数据量测试

class FixedTcpServer
    {
        private static int SendData(Socket s,byte[] data)
        {
            int total = 0;
            int size = data.Length;
            int dataleft = size;
            int sent;

            while(total<size)
            {
                sent = s.Send(data, total, dataleft, SocketFlags.None);
                total += sent;
                dataleft -= sent;
            }

            return total;
        }

        private static byte[] ReceiveData(Socket s,int size)
        {
            int total = 0;
            int dataleft = size;
            byte[] data = new byte[size];
            int recv;

            while(total<size)
            {
                recv = s.Receive(data, total, dataleft, 0);
                if(recv==0)
                {
                    data = Encoding.ASCII.GetBytes("exit");
                    break;
                }
                total += recv;
                dataleft -= recv;
            }
            return data;
        }

        public void FixedTcpServer_Run()
        {
            byte[] data = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
            Socket newSock = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            newSock.Bind(ipep);
            newSock.Listen(10);
            Console.WriteLine("等待客户端连接!");
            Socket client = newSock.Accept();

            IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
            Console.WriteLine("已连接客户端{0},对方端口为{1}", 
                newclient.Address, newclient.Port);

            string welcome = "welcome to my test server";
            data = Encoding.ASCII.GetBytes(welcome);
            int sent = SendData(client, data);

            for(int i=0;i<5;i++)
            {
                data = ReceiveData(client, 9);
                Console.WriteLine(Encoding.ASCII.GetString(data));
            }

            Console.WriteLine("断开与{0}的连接!", newclient.Address);
            client.Close();
            newSock.Close();

        }
    }

网络流测试

class StreamServer
    {
        /*
         * 网络流
         */
        public void StreamServer_Run()
        {
            string data;
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
            Socket newSock = new Socket(AddressFamily.InterNetwork, 
                SocketType.Stream, ProtocolType.Tcp);

            newSock.Bind(ipep);
            newSock.Listen(10);

            Socket client = newSock.Accept();

             
            NetworkStream ns = new NetworkStream(client);
            StreamReader sr = new StreamReader(ns);
            StreamWriter sw = new StreamWriter(ns);

            string welcome = "欢迎连接测试服务器!";
            sw.WriteLine(welcome);
            sw.Flush();

            while(true)
            {
                try
                {
                    data = sr.ReadLine();
                }
                catch(IOException)
                {
                    break;
                }
                Console.WriteLine(data);
                sw.WriteLine(data);
                sw.Flush();
            }
            Console.WriteLine("已断开与{0}的连接", (IPEndPoint)client.RemoteEndPoint);
            sw.Close();
            sr.Close();
            ns.Close();
            client.Close();
            newSock.Close();

        }
    }

UDP通信例子

class UdpSrvrSample
    {
        /*
         * UDP通信例子
         */
        public void Udp_Run()
        {
            byte[] data = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);

            UdpClient newsock = new UdpClient(ipep);
            Console.WriteLine("等待连接...");

            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);

            data = newsock.Receive(ref sender);
            Console.WriteLine("Message receive from {0}", sender.ToString());
            Console.WriteLine(Encoding.Unicode.GetString(data, 0, data.Length));

            string welcome = "欢迎连接到我的测试服务器!";
            data = Encoding.Unicode.GetBytes(welcome);
            newsock.Send(data, data.Length, sender);

            int ii = 4;

            while(ii>0)
            {
                ii -= 1;
                data = newsock.Receive(ref sender);

                Console.WriteLine(Encoding.Unicode.GetString(data, 0, data.Length));
                newsock.Send(data, data.Length, sender);
            }
        }
    }

其他例子

 class TcpPollSrvr
    {
        public void TcpPollSrvr_Run()
        {
            int recv;
            byte[] data = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);

            Socket newSock = new Socket(AddressFamily.InterNetwork, 
                SocketType.Stream, ProtocolType.Tcp);

            newSock.Bind(ipep);
            newSock.Listen(10);
            Console.WriteLine("等待来自客户端的连接...");
            bool result;

            int i = 0;
            while(true)
            {
                i++;
                Console.WriteLine("pollong for accpet#{0}", i);
                result = newSock.Poll(1000000, SelectMode.SelectRead);

                if(result)
                {
                    break;
                }
            }

            Socket client = newSock.Accept();
            IPEndPoint newClient = (IPEndPoint)client.RemoteEndPoint;

            string welcome = "欢迎连接我的测试服务器!";
            data = Encoding.ASCII.GetBytes(welcome);
            client.Send(data, data.Length, SocketFlags.None);

            i = 0;
            while(true)
            {
                Console.WriteLine("polling for recive #{0}...", i);
                i++;
                result = client.Poll(3000000, SelectMode.SelectRead);
                if(result)
                {
                    data = new byte[1024];
                    i = 0;
                    recv = client.Receive(data);
                    if (recv == 0)
                        break;
                    Console.WriteLine(
                        Encoding.Unicode.GetString(data, 0, recv));
                    client.Send(data, recv, 0);
                }
            }
            Console.WriteLine("断开与{0}的连接!", newClient.Address);
            client.Close();
            newSock.Close();
        }
    }

    class SelectTcpServer
    {
        public void SelectTcpServer_Run()
        {
            ArrayList sockList = new ArrayList(2);
            ArrayList copyList = new ArrayList(2);

            Socket main = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 9050);

            byte[] data = new byte[1024];
            string stringData;
            int recv;

            main.Bind(ipe);
            main.Listen(2);

            Socket client1 = main.Accept();
            IPEndPoint ipe1 = (IPEndPoint)client1.RemoteEndPoint;

            client1.Send(Encoding.Unicode.GetBytes("欢迎连接我的测试服务器!"));
            Console.WriteLine("以连接到{0}", ipe1.ToString());

            sockList.Add(client1);

            Console.WriteLine("等待新的客户端连接!");
            Socket client2 = main.Accept();
            IPEndPoint ipe2 = (IPEndPoint)client2.RemoteEndPoint;
            client2.Send(Encoding.Unicode.GetBytes("欢迎连接我的测试服务器!"));
            Console.WriteLine("新加入一个来自{0}的连接!", ipe2.ToString());

            sockList.Add(client2);
            main.Close();

            while(true)
            {
                copyList = new ArrayList(sockList);
                Console.WriteLine("监测到{0}个客户端!", copyList.Count);
                Socket.Select(copyList, null, null, 10000000);
                
                foreach(Socket client in copyList)
                {
                    data = new byte[1024];
                    recv = client.Receive(data);
                    stringData = Encoding.Unicode.GetString(data, 0, recv);
                    Console.WriteLine("接收到信息:\n{0}",stringData);

                    if (recv == 0)
                    {
                        ipe = (IPEndPoint)client.RemoteEndPoint;
                        Console.WriteLine("客户端{0}无连接!", ipe.ToString());
                        client.Close();
                        sockList.Remove(client);
                        if (sockList.Count == 0)
                        {
                            Console.WriteLine("断开和最后一个客户端的连接,再见!");
                            return;
                        }
                    }
                    else
                        client.Send(data, recv, SocketFlags.None);
                }
            }


        }
    }
  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-10-20 12:51:43  更:2021-10-20 12:52:53 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/26 4:50:54-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码