首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从服务器发送消息和从客户端接收消息

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

Stack Overflow用户
提问于 2015-09-28 02:25:14
回答 2查看 10K关注 0票数 0

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

代码语言:javascript
运行
复制
string[] arr1 = new string[] { "one", "two", "three" };

我需要用下面的服务器和客户端代码添加哪些额外的代码?

代码语言:javascript
运行
复制
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);
      }
    }
  }
}
EN

回答 2

Stack Overflow用户

发布于 2015-09-28 02:43:31

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

这里有一个你可以应用于你的模型的简化:

服务器端:

代码语言:javascript
运行
复制
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.
}

客户端:

代码语言:javascript
运行
复制
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. 发送string[]的长度。示例:writer.WriteLine(myArray.Length.ToString);
  2. Receive和parse this length
  3. 在服务器端一个接一个地发送所有字符串
  4. 在客户端接收for循环中的所有字符串。

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

票数 1
EN

Stack Overflow用户

发布于 2015-09-28 02:48:40

将字符串数组发送到客户端

代码语言:javascript
运行
复制
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);

            }               
        }

客户端

代码语言:javascript
运行
复制
         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();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32811339

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档