I am developing an application in which, with a sharp server, it communicates with the android client. The server needs to send several messages in Android tcpClient. As for sending the message, I have to close the tcpClient object on the server. otherwise it is not sent. As soon as tcpClient closes, how can I contact my client again, how can I track and send multiple messages as soon as I close tcpClient, or is there another way to send without closing it. If the question remains unclear, please comment below.
it sends one easlity message, but I need to send more messages from time to time
Here is a snippet of code for the 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(); } } }
Raheel sadiq
source share