8

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

它发送一条消息很容易,但我需要不时发送更多消息

这是服务器的代码片段

//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();
    }
}
}
4

1 回答 1

3

试试这个:

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

}
于 2012-10-13T19:51:10.660 回答