从TCP服务器向客户端发送多条消息(C sharp to Android)

时间:2021-10-09 09:50:16

I am developing an app, in which c sharp server communicates with android client. Server needs to send multiple message to the Android tcpClient. As to send message I have to close the tcpClient Object on the server. otherwise it does not send. Once tcpClient is closed how can i communicate with my client again , how can i keep track and send multiple messages, once i close tcpClient, or there is any other way of sending without closing it. If the question is still unclear, please comment below

我正在开发一个应用程序,其中c sharp服务器与android客户端通信。服务器需要向Android tcpClient发送多条消息。至于发送消息,我必须关闭服务器上的tcpClient对象。否则它不会发送。一旦tcpClient关闭,我怎么能再次与我的客户端通信,如何关闭tcpClient,或者有任何其他方式发送而不关闭它,我如何跟踪并发送多条消息。如果问题仍不清楚,请在下面发表评论

it sends one message easlity but i need to send more messages from time to time

它发送一个消息easlity但我需要不时发送更多的消息

Here is the snippet of code for server

这是服务器的代码片段

//in a thread
void receivingMessages(object param)
    {
        try
        {
            var paramArray = (object[])param;
            var id = paramArray[0];
            var client = paramArray[1] as TcpClient;

            var stream = client.GetStream();

            while (true)
            {
                byte[] buffer = new byte[2048];
                int bytesRead = stream.Read(buffer, 0, 2048);

                if (bytesRead > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    string v = Encoding.ASCII.GetString(buffer);

                    int index = v.IndexOf('\0');
                    string trimmedXml = v.TrimEnd(new char[] { '\0' });

                    var root = XDocument.Parse(trimmedXml).Root;
                    //to get the type of xml like it is login register or message
                    string xmlType = root.Name.ToString();

                    //some checks     
                    string result = " server messages";
                    SendMessage(client, result);

                }

                //Thread.Sleep(10);
            }
        }
        catch (Exception)
        {

        }

    }


    public void SendMessage(TcpClient client, string message)
    {

        byte[] buffer = Encoding.ASCII.GetBytes(message);

        NetworkStream stream = client.GetStream();
        stream.Write(buffer, 0, buffer.Length);

        client.Close();
    }
}
}

1 个解决方案

#1


3  

Try this:

尝试这个:

public void SendMessage(TcpClient client, string message)
{

    //byte[] buffer = Encoding.ASCII.GetBytes(message);

    NetworkStream stream = client.GetStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.WriteLine(message);
    writer.Flush();

}

#1


3  

Try this:

尝试这个:

public void SendMessage(TcpClient client, string message)
{

    //byte[] buffer = Encoding.ASCII.GetBytes(message);

    NetworkStream stream = client.GetStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.WriteLine(message);
    writer.Flush();

}