c# script能實(shí)現(xiàn)網(wǎng)絡(luò)通信嗎

c#
小樊
81
2024-09-28 05:40:59

是的,C#腳本可以實(shí)現(xiàn)網(wǎng)絡(luò)通信。在C#中,可以使用System.Net和System.Net.Sockets命名空間中的類來(lái)實(shí)現(xiàn)網(wǎng)絡(luò)通信。這些類提供了用于創(chuàng)建客戶端和服務(wù)器應(yīng)用程序的框架,以及用于發(fā)送和接收數(shù)據(jù)的方法。

以下是一個(gè)簡(jiǎn)單的C#服務(wù)器示例,該示例使用TcpListener類監(jiān)聽來(lái)自客戶端的連接:

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

class Server
{
    static void Main()
    {
        int port = 12345;
        TcpListener server = null;

        try
        {
            server = new TcpListener(IPAddress.Any, port);
            server.Start();

            Console.WriteLine("Server started...");

            while (true)
            {
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Client connected...");

                NetworkStream stream = client.GetStream();
                byte[] data = new byte[256];
                int i = stream.Read(data, 0, data.Length);

                string received = Encoding.ASCII.GetString(data, 0, i);
                Console.WriteLine("Received: " + received);

                string response = "Hello from server!";
                byte[] msg = Encoding.ASCII.GetBytes(response);

                stream.Write(msg, 0, msg.Length);
                Console.WriteLine("Sent: " + response);

                client.Close();
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: " + e.Message);
        }
        finally
        {
            if (server != null)
            {
                server.Stop();
            }
        }
    }
}

此外,還可以使用HttpClient類進(jìn)行HTTP通信,或使用WCF(Windows Communication Foundation)進(jìn)行更復(fù)雜的網(wǎng)絡(luò)通信。

0