📜  电话 - C# (1)

📅  最后修改于: 2023-12-03 15:11:21.324000             🧑  作者: Mango

电话 - C#

电话是一种通信方式,可通过计算机程序进行控制和操作。在C#中,我们可以使用System.Net.Sockets命名空间来实现电话通信的功能。

客户端实现

通过C#编写客户端代码,使用Socket类建立与服务器端的连接,并使用StreamReader和StreamWriter对传入和传出的数据进行处理。下面是一个例子:

using System;
using System.IO;
using System.Net.Sockets;

class Client{
  public static void Main(){
    try{
      TcpClient client = new TcpClient("localhost", 8888);
      Console.WriteLine("Connected to server.");
      NetworkStream stream = client.GetStream();
      StreamReader reader = new StreamReader(stream);
      StreamWriter writer = new StreamWriter(stream);
      writer.AutoFlush = true;
      
      Console.Write("Enter a message: ");
      string message = Console.ReadLine();
      writer.WriteLine(message);

      string response = reader.ReadLine();
      Console.WriteLine("Server response: {0}", response);

      reader.Close();
      writer.Close();
      stream.Close();
      client.Close();
      
      Console.ReadKey();
    }
    catch(Exception e){
      Console.WriteLine("Error: {0}", e);
    }
  }
}
服务器端实现

服务器端应用程序使用TcpListener类来接受客户端连接,并使用StreamReader和StreamWriter对传入和传出的数据进行处理。下面是一个例子:

using System;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Threading;

class Server{
  public static void Main(){
    TcpListener server = null;
    try{
      server = new TcpListener(IPAddress.Any, 8888);
      server.Start();
      Console.WriteLine("Server started, listening for connections...");
      
      while(true){
        TcpClient client = server.AcceptTcpClient();
        Console.WriteLine("Client connected.");
        ThreadPool.QueueUserWorkItem(ThreadProc, client);
      }
    }
    catch(Exception e){
      Console.WriteLine("Error: {0}", e);
    }
    finally{
      server.Stop();
    }
  }
  
  private static void ThreadProc(object obj){
    TcpClient client = (TcpClient)obj;
    NetworkStream stream = client.GetStream();
    StreamReader reader = new StreamReader(stream);
    StreamWriter writer = new StreamWriter(stream);
    writer.AutoFlush = true;
    
    string message = reader.ReadLine();
    Console.WriteLine("Message received: {0}", message);
    writer.WriteLine("Message received: {0}", message);
    
    reader.Close();
    writer.Close();
    stream.Close();
    client.Close();
  }
}

这是一个简单的电话程序示例。通过C#编写客户端和服务器端应用程序,可以实现不同计算机间的电话通信。