C# 从TCP服务器向客户端发送多条消息(C sharp到Android)
我正在开发一个应用程序,其中c sharp服务器与android客户端进行通信。 服务器需要向Android tcpClient发送多条消息。至于发送消息,我必须关闭服务器上的tcpClient对象。否则它不会发送。一旦tcpClient关闭,我如何再次与我的客户端通信,如何跟踪并发送多条消息,一旦我关闭tcpClient,或者有任何其他发送方式而不关闭它。 如果问题仍然不清楚,请在下面进行评论 它发送一条消息很简单,但我需要不时发送更多消息 下面是服务器的代码片段C# 从TCP服务器向客户端发送多条消息(C sharp到Android),c#,android,sockets,tcpclient,tcplistener,C#,Android,Sockets,Tcpclient,Tcplistener,我正在开发一个应用程序,其中c sharp服务器与android客户端进行通信。 服务器需要向Android tcpClient发送多条消息。至于发送消息,我必须关闭服务器上的tcpClient对象。否则它不会发送。一旦tcpClient关闭,我如何再次与我的客户端通信,如何跟踪并发送多条消息,一旦我关闭tcpClient,或者有任何其他发送方式而不关闭它。 如果问题仍然不清楚,请在下面进行评论 它发送一条消息很简单,但我需要不时发送更多消息 下面是服务器的代码片段 //in a thread
//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();
}
}
}
试试这个:
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();
}
@L.B在我听来,他在不关闭流的情况下无法发送消息,但他想让它保持打开状态:“有没有办法在不关闭的情况下发送…”所以我重写了它来编写消息,但没有关闭。@0 uuuuuuuuuuuuuuuu0仍然无法发送消息,除非我关上它tcpclient@mindFreezer也许可以尝试设置
client.NoDelay=true
在SendMessage方法中,我测试了我的代码,它运行得很好,所以我不确定是哪里出了问题。@0\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。。。