是的,C#脚本可以实现网络通信。在C#中,可以使用System.Net和System.Net.Sockets命名空间中的类来实现网络通信。这些类提供了用于创建客户端和服务器应用程序的框架,以及用于发送和接收数据的方法。
以下是一个简单的C#服务器示例,该示例使用TcpListener类监听来自客户端的连接:
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类进行HTTP通信,或使用WCF(Windows Communication Foundation)进行更复杂的网络通信。