1. Socket network programming to establish Server and Client connections

Starting today, I will write a lot of learning records to tackle socket network programming!

Based on the C/S structure, server and client are indispensable for socket network compilation.

Table of contents

Compilation stage:

Testing phase:

Compilation stage:

First create a project, name it Server, refer to the necessary space, and then compile it in the Main function as follows:

Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建服务端的socket
            IPAddress iphost = IPAddress.Parse("127.0.0.1");
            server.Bind(new IPEndPoint(iphost, 2020));  //绑定监听端口
            server.Listen(10); //开始设置10个监听位置
            Console.WriteLine("监听开始...");

            while (true)
            {
                Socket client = server.Accept();
                Console.WriteLine("有客户端进入:" + client.LocalEndPoint);
            }

After the server is created, create another project in the same way and name it Client. After the namespace is referenced, write the Client project. The code is as follows:

IPAddress hostIp = IPAddress.Parse("127.0.0.1");
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  //创建客户端的socket
            try
            {
                client.Connect(new IPEndPoint(hostIp, 2020));  //尝试连接服务端
                Console.WriteLine("连接成功");
            }
            catch
            {
                Console.WriteLine("连接失败");
            }

Testing phase:

1. Do not open the server, to use the client

 

2. Open the server and use the client.

 

 

 

Guess you like

Origin blog.csdn.net/m0_64810555/article/details/125667147