gpt4 book ai didi

c# - 取决于服务代理的 TCP 套接字服务器,我如何接收整个消息并发送响应?

转载 作者:可可西里 更新时间:2023-11-01 02:55:13 25 4
gpt4 key购买 nike

我正在设置一个需要做几件事的应用程序... 1.) 从 tcp 套接字接收一串 xml 数据。 2.) 将此数据插入 sql 表中。 3.) 触发器更新这些表中的大量内容并将它们放入输出表中。 4.) Sql Dependencies 确认记录已插入输出表,需要通过相同的套接字发送回复。

我遇到的问题是,如果我从客户端将整个消息发送到服务器,我必须.Close 客户端,这使得无法收到响应,如果我不 .Close 客户端,只要消息适合一个数据包,我就可以收到响应(如果消息太长,服务器接收的消息将被切断,因此抛出一个错误)。我怎样才能使这项工作?所以现在不知所措,如果需要任何其他信息来帮助这项工作,请告诉我。我接近这个项目的最后期限,真的很想让它发挥作用。

这是我的客户端代码:

private void SendMessage(string input, TcpClient client)
{
// Ensure some xml data has been provided.
string Error = string.Empty;
if (input == string.Empty)
{
Error += "You cannot send an empty xml string\r";
Textbox_FauxXMLSend.Focus();
}

// Prompt user to correct data if needed.
if (Error != string.Empty)
{
MessageBox.Show(Error, "Send XML", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}

try
{
// Send and receive the provided xml data.
using (NetworkStream networkStream = client.GetStream())
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(input + "\0");
networkStream.Write(outStream, 0, outStream.Length);
networkStream.Flush();
byte[] inStream = new byte[10025];
networkStream.Read(inStream, 0, (int)client.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
Textbox_FauxXMLReceive.Text += (returndata) + "\n";
}
_requestCount++;
lblRequestCount.Text = string.Format("Request Count: {0}", _requestCount.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Send Message Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
CloseConnection(client);
}
}

服务端接收端:

private void ReceivePortMessages()
{
string debug = string.Empty;
try
{
Debug.Print(" >> Starting Server");
IPAddress ipAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
_TcpListener = new TcpListener(ipAddress, TcpPort); ;
Debug.Print(string.Format("{0}:{1}", ipAddress.ToString(), TcpPort.ToString()));
_TcpListener.Start();

Stopwatch sw = new Stopwatch();
do
{
try
{
_TcpClient = _TcpListener.AcceptTcpClient();
Debug.Print(" >> Accept connection from client");
NetworkStream networkStream = _TcpClient.GetStream();
int receivingBufferSize = (int)_TcpClient.ReceiveBufferSize;
byte[] bytesFrom = new byte[receivingBufferSize];
int Read = 0;
string dataFromClient = string.Empty;
if (!sw.IsRunning)
{
sw.Start();
}

Read = networkStream.Read(bytesFrom, 0, receivingBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0"));
if (dataFromClient != string.Empty)
{
XmlDocument xm = new XmlDocument();
debug = dataFromClient;
xm.LoadXml(string.Format("<root>{0}</root>", dataFromClient));
XmlElement root = xm.DocumentElement;
string rootName = root.FirstChild.Name;
RouteInboundXML(rootName, dataFromClient, sw);
sw.Restart();
}
}
catch (Exception ex)
{
Debug.Print("ReceivePortMessages: " + ex.ToString());
_TcpClient.Close();
_TcpListener.Stop();
ErrorLog.Write("XmlProcessing", ex.ToString() + "\r\n" + "DataFromClient: " + debug, "ReceivePortMessages()");
return;
}
} while (true);
}
catch (Exception ex)
{
Debug.Print("ReceivePortMessages: " + ex.ToString());
ErrorLog.Write("XmlProcessing", ex.ToString(), "ReceivePortMessages()");
}
}

在触发 SqlDependency 操作并生成适当的数据后调用服务器的发送:

private void SendReply(string reply)
{
try
{
NetworkStream networkStream = _TcpClient.GetStream();
string serverResponse = reply;
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Debug.Print(" >> " + serverResponse);
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
ErrorLog.Write("XmlProcessing", ex.ToString(), "SendReply()");
}
}

最佳答案

The problem I am running into is this, if I get the entire message sent to the server from the client, I have to .Close the client side, which makes it impossible to receive a response

当然,如果您在向服务器发送消息时关闭套接字,客户端将不会收到响应。

if I don't .Close the client side, I can receive responses as long as the message fits into one packet (message being received by the server is cut off if it's too long and therefor throws an error).

TCP 是流协议(protocol),不维护消息边界。您的客户端不能假设来自服务器的响应将适合一个数据包。它应该知道服务器响应。对于这个服务器和客户端应该有一个协议(protocol)。喜欢:

how many bytes does the response take? Put this info in the messages getting exchanged.

Markers enclosing the response message - Start of message and end of message.

基于这些知识,客户端应该“预期”可以通过多个read 操作得到的响应。所以实际上,你不能只有一个read。您应该继续调用 read,直到根据应用程序级别的理解读取所需的字节数。

关于c# - 取决于服务代理的 TCP 套接字服务器,我如何接收整个消息并发送响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30326488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com