温馨提示×

C#如何实现TCP/IP通信

c#
小樊
81
2024-09-14 23:25:25
栏目: 编程语言

在C#中,可以使用System.Net.Sockets命名空间中的类来实现TCP/IP通信。下面是一个简单的示例,展示了如何创建一个TCP服务器和客户端进行通信。

首先,我们创建一个TCP服务器:

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

namespace TcpServer
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建一个TcpListener实例,监听指定的IP地址和端口
            TcpListener server = new TcpListener(IPAddress.Any, 8080);
            server.Start();

            Console.WriteLine("服务器已启动,等待客户端连接...");

            while (true)
            {
                // 当有客户端连接时,接受连接并返回一个TcpClient实例
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("客户端已连接:" + client.Client.RemoteEndPoint);

                // 获取客户端的网络流
                NetworkStream stream = client.GetStream();

                // 读取客户端发送的数据
                byte[] data = new byte[256];
                int i = stream.Read(data, 0, data.Length);

                // 将接收到的数据转换为字符串
                string receivedData = Encoding.ASCII.GetString(data, 0, i);
                Console.WriteLine("接收到的数据: " + receivedData);

                // 向客户端发送响应
                string response = "服务器已收到数据: " + receivedData;
                data = Encoding.ASCII.GetBytes(response);
                stream.Write(data, 0, data.Length);

                // 关闭客户端连接
                client.Close();
            }
        }
    }
}

接下来,我们创建一个TCP客户端:

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

namespace TcpClient
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建一个TcpClient实例,连接到服务器
            TcpClient client = new TcpClient("127.0.0.1", 8080);

            // 获取服务器的网络流
            NetworkStream stream = client.GetStream();

            // 向服务器发送数据
            string sendData = "你好,这是一条来自客户端的消息!";
            byte[] data = Encoding.ASCII.GetBytes(sendData);
            stream.Write(data, 0, data.Length);

            // 从服务器接收响应
            data = new byte[256];
            int i = stream.Read(data, 0, data.Length);

            // 将接收到的数据转换为字符串
            string receivedData = Encoding.ASCII.GetString(data, 0, i);
            Console.WriteLine("接收到的响应: " + receivedData);

            // 关闭客户端连接
            client.Close();
        }
    }
}

运行上述代码,首先启动TCP服务器,然后启动TCP客户端。服务器将接收到客户端发送的数据,并向客户端发送响应。客户端将接收到服务器的响应并显示在控制台上。

0