【Csharp】使用Csharp读取Tcp数据

   |   1 minute read   |   Using 96 words

使用Csharp读取Tcp数据

// See https://aka.ms/new-console-template for more information

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

Console.WriteLine("Hello, World!");

try
{
    // Set up the client socket
    using (Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
    {
        // Connect to the server
        IPAddress serverIP = IPAddress.Parse("127.0.0.1"); // Server IP address
        IPEndPoint serverEndPoint = new IPEndPoint(serverIP, 12345); // Server port
        clientSocket.Connect(serverEndPoint);

        while (true)
        {
            // Receive and display messages
            byte[] buffer = new byte[1024];
            int bytesReceived = clientSocket.Receive(buffer);
            string message = Encoding.UTF8.GetString(buffer, 0, bytesReceived);
            Console.WriteLine("Received: " + message);
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine("An error occurred: " + ex.Message);
}



© 2025 by clayliu. All Rights Reserved.