从服务器端发送消息,从客户端接收消息

本文关键字:消息 客户端 端接 客户 服务器端 | 更新日期: 2023-09-27 18:14:39

下面是一个用c#编写的示例服务器程序,它从客户端接收id。我的示例代码如下所示。我想发送一个字符串数组到客户端,并显示在客户端控制台上。示例数组字符串可以是:

string[] arr1 = new string[] { "one", "two", "three" };

我需要在以下服务器和客户端代码中添加哪些其他代码?

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace server
{
  class Program
  {
    static void Main(string[] args)
    {
      TcpListener tcpListener = new TcpListener(IPAddress.Any, 1234);
      tcpListener.Start();
      while (true)
      {
        TcpClient tcpClient = tcpListener.AcceptTcpClient();
        byte[] data = new byte[1024];
        NetworkStream ns = tcpClient.GetStream();
        int recv = ns.Read(data, 0, data.Length);
        string id = Encoding.ASCII.GetString(data, 0, recv);
        Console.WriteLine(id);
      }
    }
  }
}

从服务器端发送消息,从客户端接收消息

由于Tcp是基于流的协议,我建议您使用比普通byte[]更高级别的协议。如果所有你需要的是发送字符串从客户端到服务器,反之亦然,我认为StreamReaderStreamWriter两端将工作得很好。在StreamWriter端,您有一个WriteLine(string)方法要发送给客户端,StreamReader有一个类似的ReadLine()方法。

这是一个简化,你可以应用到你的模型:

服务器端:

TcpClient client; //Let's say it's already initialized and connected properly
StreamReader reader = new StreamReader(client.GetStream());
while(client.Connected)
{
    string message = reader.ReadLine(); //If the string is null, the connection has been lost.
}

客户端:

TcpClient client; //Same, it's initialized and connected
StreamWriter writer = new StreamWriter(client.GetStream());
writer.AutoFlush = true; //Either this, or you Flush manually every time you send something.
writer.WriteLine("My Message"); //Every message you want to send

StreamWriter将以新行结束每条消息,以便StreamReader知道何时接收到完整的字符串。

注意TCP连接是全双工连接。这意味着你可以同时发送和接收数据。如果您想实现类似的内容,请检查WriteLineAsync(string)ReadLineAsync()方法。

如果你想发送数组,建立一个简单的协议,看起来有点像这样:

  1. 发送字符串[]的长度。示例:writer.WriteLine(myArray.Length.ToString);
  2. 接收并解析此长度
  3. 在服务器端依次发送所有字符串
  4. 接收客户端for循环中的所有字符串

收到所有字符串后,重复此过程。

发送字符串数组到客户端

TcpListener tcpListener = new TcpListener(IPAddress.Any, 1234);
        tcpListener.Start();  
        while (true)
        {                     
            TcpClient tcpClient = tcpListener.AcceptTcpClient();
            byte[] data = new byte[1024];
            NetworkStream ns = tcpClient.GetStream();
            string[] arr1 = new string[] { "one", "two", "three" };
            var serializer = new XmlSerializer(typeof(string[]));
            serializer.Serialize(tcpClient.GetStream(), arr1);
            tcpClient.GetStream().Close()
            tcpClient.Close();
              int recv = ns.Read(data, 0, data.Length);
               in this line
            string id = Encoding.ASCII.GetString(data, 0, recv);
            Console.WriteLine(id);
            }               
        }
客户

         try
         {
            byte[] data = new byte[1024];
            string stringData;
            TcpClient tcpClient = new TcpClient("127.0.0.1", 1234);
            NetworkStream ns = tcpClient.GetStream();             
            var serializer = new XmlSerializer(typeof(string[]));
            var stringArr = (string[])serializer.Deserialize(tcpClient.GetStream());
            foreach (string s in stringArr)
            {
                Console.WriteLine(s);
            }
            string input = Console.ReadLine();
            ns.Write(Encoding.ASCII.GetBytes(input), 0, input.Length);
            ns.Flush();

        }
        catch (Exception e)
        {
            Console.Write(e.Message);
        }
        Console.Read();