Sending message from server and receive from the client end

本小妞迷上赌 提交于 2020-01-17 05:01:11

问题


Here is a sample server program written in c# which receives an id from a client. My sample code is given below. I want to send a string array to client and display is on the client console. The sample array string can be:

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

What additional code I need to add with the following server and client code?

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);
      }
    }
  }
}

回答1:


Since Tcp is a stream based protocol, I would suggest you use something higher level that plain byte[]. If all you need is to send strings from client to server and vice-versa, I think a StreamReader and a StreamWriter on both ends would work great. On the StreamWriter side, you've got a WriteLine(string) method to send to the client and the StreamReader has a similar method ReadLine().

Here's a simplification that you could apply to your model:

Server side:

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.
}

Client side:

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 will end every message with a new line so that the StreamReader knows when the full string has been received.

Note that a TCP connection is a full-duplex connection. Meaning you can simultaneously send and receive data. Checkout the WriteLineAsync(string) and ReadLineAsync() methods if you want to implement something like this.

If you want to send arrays, establish a simple protocol looking a bit like this:

  1. Send the length of the string[]. Example: writer.WriteLine(myArray.Length.ToString);
  2. Receive and parse this length
  3. Send all strings one after the other on the server side
  4. Receive all strings in a for loop on the client side.

Once you received all strings, repeat the process.




回答2:


Sending String Array to client

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);

            }               
        }

Client

         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();


来源:https://stackoverflow.com/questions/32811339/sending-message-from-server-and-receive-from-the-client-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!