【C#】Socket实现服务器端和客户端通信

新建两个项目,一个服务器端,一个客户端

 

创建服务器

static void Main(string[] args)
{
    //创建一个服务器
    Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    IPAddress iPAddress = IPAddress.Parse("192.168.1.105");
    IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, 8888);

    //绑定IP和端口号
    serverSocket.Bind(iPEndPoint);

    //监听端口
    serverSocket.Listen(0);

    //创建客户端连接
    Socket clientSocket = serverSocket.Accept();

    //向客户端发送一条信息
    string msg = "Hello client!";
    byte[] data = Encoding.UTF8.GetBytes(msg);
    clientSocket.Send(data);

    //接收客户端一条信息
    byte[] dataBuffer = new byte[1024];
    int count = clientSocket.Receive(dataBuffer);
    string msgReceive = Encoding.UTF8.GetString(dataBuffer, 0, count);
    Console.WriteLine(msgReceive);

    clientSocket.Close();
    serverSocket.Close();

    Console.ReadKey();
}

创建客户端

static void Main(string[] args)
{
    //创建客户端
    Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    IPAddress iPAddress = IPAddress.Parse("192.168.1.105");
    IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, 8888);
    //连接服务器
    clientSocket.Connect(iPEndPoint);

    //接收服务器一条信息
    byte[] data = new byte[1024];
    int count = clientSocket.Receive(data);
    string msg = Encoding.UTF8.GetString(data, 0, count);
    Console.WriteLine(msg);

    //向服务器发送一条信息
    string str = Console.ReadLine();
    clientSocket.Send(Encoding.UTF8.GetBytes(str));

    clientSocket.Close();

    Console.ReadKey();
}

首先,开启一个服务器端,在开启客户端

开启客户端后,接收到服务器端发送的消息,接着输入内容想服务器发送消息

但是这样不能实现连续发送消息的功能,接下来将实现多个客户端连接且连续发送消息

服务器

static void Main(string[] args)
{
    //创建一个服务器
    Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    IPAddress iPAddress = IPAddress.Parse("192.168.1.105");
    IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, 8888);

    //绑定IP和端口号
    serverSocket.Bind(iPEndPoint);

    //监听端口
    serverSocket.Listen(0);

    //接收一个客户端连接
    serverSocket.BeginAccept(AcceptCallBack, serverSocket);

    Console.ReadKey();
    serverSocket.Close();
}
//接收客户端连接回调
static void AcceptCallBack(IAsyncResult result)
{
    Socket serverSocket = result.AsyncState as Socket;
    Socket clientSocket = serverSocket.EndAccept(result);

    //向客户端发送一条信息
    string msg = "Hello client!";
    byte[] data = Encoding.UTF8.GetBytes(msg);
    clientSocket.Send(data);

    //接收客户端数据
    clientSocket.BeginReceive(dataBuffer, 0, 1024, SocketFlags.None, ReceiveCallBack, clientSocket);
    //继续接收连接
    serverSocket.BeginAccept(AcceptCallBack, serverSocket);
}

static byte[] dataBuffer = new byte[1024];
//接收客户端消息回调
static void ReceiveCallBack(IAsyncResult result)
{
    Socket clientSocket = null;
    try
    {
        clientSocket = result.AsyncState as Socket;
        int count = clientSocket.EndReceive(result);
        if (count == 0)
        {
            clientSocket.Close();
            return;
        }
        string msg = Encoding.UTF8.GetString(dataBuffer, 0, count);
        Console.WriteLine("从客户端接收的数据:" + msg);
        //继续接收数据
        clientSocket.BeginReceive(dataBuffer, 0, 1024, SocketFlags.None, ReceiveCallBack, clientSocket);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        clientSocket.Close();
    }
}

客户端

static void Main(string[] args)
{
    //创建客户端
    Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    IPAddress iPAddress = IPAddress.Parse("192.168.1.105");
    IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, 8888);
    //连接服务器
    clientSocket.Connect(iPEndPoint);

    //接收服务器一条信息
    byte[] data = new byte[1024];
    int count = clientSocket.Receive(data);
    string msg = Encoding.UTF8.GetString(data, 0, count);
    Console.WriteLine(msg);

    //向服务器发送信息
    while (true)
    {
        try
        {
            string str = Console.ReadLine();
            //关闭
            if (str == "c")
            {
                clientSocket.Close();
                return;
            }

            clientSocket.Send(Encoding.UTF8.GetBytes(str));
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

启动服务器端和多个客户端进行连续发送消息

 

相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页