Socket通信基本流程(C#)

 1.服务器端代码

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

namespace Socket_ServerTcp
{
    class Program
    {
        static void Main(string[] args)//string[] args命令行(黑框框)里输入的参数
        {
            //1.创建服务端的socket对象(监听客户端连接)
            Socket ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress iPAddress = IPAddress.Parse("192.168.56.1");
            System.Net.EndPoint endpoint = new IPEndPoint(iPAddress, 8055);

            //2.绑定ip和端口
            ServerSocket.Bind(endpoint);
            Console.WriteLine("服务器启动成功。。。");
            //3.监听
            ServerSocket.Listen(100);
            Console.WriteLine("服务器开始监听。。。");

            while (true)
            { 
                //4.等待接受客户端连接(返回用于和客户端通信的socket)
                 Socket newSocket= ServerSocket.Accept();
                Console.WriteLine("客户端连接成功,IP:",newSocket.RemoteEndPoint);
                //5.接受消息
                byte[] data = new byte[1024];
                newSocket.Receive(data);
                //6.发送
                newSocket.Send(data);
                //7.关闭socket
                //newSocket.Close();
            }



        }
    }

}


2.客户端代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Socket_ServerTcp
{
    class Program
    {
        static void Main(string[] args)
        {
            //1.创建客户端的socket对象(和服务端连接通讯)
            Socket ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress iPAddress = IPAddress.Parse("192.168.56.1");
            System.Net.EndPoint endpoint = new IPEndPoint(iPAddress, 8055);

            //2.连接服务器
            ClientSocket.Connect(endpoint);
            Console.WriteLine("客户端连接成功。。。");

            //3.发送
            byte[] data = new byte[1024];
            ClientSocket.Send(data);
            //4.接收
            ClientSocket.Receive(data);
            //5.关闭socket
            //newSocket.Close();

       



        }
    }

}


代码来源:02.Socket通信基本流程演示_哔哩哔哩_bilibili

猜你喜欢

转载自blog.csdn.net/weixin_45348216/article/details/128088098