温馨提示×

C# TcpIp编程基础入门指南

c#
小樊
99
2024-07-22 21:48:06
栏目: 编程语言

TCP/IP编程是一种网络编程技术,用于在计算机之间进行通信。在C#中,可以使用System.Net命名空间中的类来实现TCP/IP编程。以下是一个基础的入门指南,帮助您开始使用C#进行TCP/IP编程:

  1. 创建一个TCP服务器:

    using System;
    using System.Net;
    using System.Net.Sockets;
    
    class TCPServer
    {
        static void Main(string[] args)
        {
            TcpListener listener = new TcpListener(IPAddress.Any, 1234);
            listener.Start();
            
            Console.WriteLine("Server started, waiting for connections...");
            
            TcpClient client = listener.AcceptTcpClient();
            Console.WriteLine("Client connected!");
            
            NetworkStream stream = client.GetStream();
            byte[] data = new byte[1024];
            int bytesRead = stream.Read(data, 0, data.Length);
            string message = System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);
            Console.WriteLine("Received: " + message);
            
            client.Close();
            listener.Stop();
        }
    }
    
  2. 创建一个TCP客户端:

    using System;
    using System.Net;
    using System.Net.Sockets;
    
    class TCPClient
    {
        static void Main(string[] args)
        {
            TcpClient client = new TcpClient("127.0.0.1", 1234);
            NetworkStream stream = client.GetStream();
            
            string message = "Hello, server!";
            byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
            stream.Write(data, 0, data.Length);
            
            client.Close();
        }
    }
    
  3. 运行服务器和客户端代码,并确保它们可以相互通信。

这只是一个简单的示例,您可以根据自己的需求和场景进行扩展和修改。TCP/IP编程涉及到很多复杂的概念和技术,建议您深入学习这些知识,以便能够更好地应用到实际项目中。希望这个基础入门指南能帮助您开始使用C#进行TCP/IP编程。

0