我正在开发客户端-服务器多线程应用程序:
沟通的进展是:
- 服务器侦听套接字
- 客户端连接并向服务器发送请求或请求
- 每个请求都以 0x04 结束
- 服务器必须使用比传入请求慢的操作来处理每个请求
当两个请求在短时间内发生并且由于第二个请求即将处理而无法处理第一个请求直到方法结束时,我在“ProcessClient”方法中遇到问题。foreach 循环后出现问题:
foreach (var t in invoices)
{
SaveToDataBase(t);
}
方法直到最后才会执行,并且不会使用以下代码片段向客户端发送响应:
var ResponseFile = ResponseClientFolder + "\\" + ResponseClientFileName + x + ".txt";
StreamWriter sw = File.CreateText(ResponseFile);
sw.WriteLine(_odgovor);
sw.Close();
_odgovor = string.Empty;
SendToClient(ResponseFile);
因为第二个请求发生在“ProcessClient”方法中。
有什么办法可以解决这个问题。我一直在寻找许多没有成功的解决方案。
整个代码如下:
private void RunListener()
{
try
{
_listener = new TcpListener(IPAddress.Parse(ServerAddres), ServerPort);
_listener.Start();
while (true)
{
TcpClient client = _listener.AcceptTcpClient();
Invoke(new Action(() => { }));
ThreadPool.QueueUserWorkItem(ProcessClient, client);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, @"Run listener");
}
}
private void ProcessClient(object state)
{
try
{
byte[] bytes = new byte[1024];
TcpClient client = state as TcpClient;
StringBuilder completeMessage = new StringBuilder();
if (client == null) return;
networkStream = client.GetStream();
int bytesRead = 0;
do
{
bytesRead = networkStream.Read(bytes, 0, bytes.Length);
completeMessage.AppendFormat("{0}", Encoding.Default.GetString(bytes, 0, bytesRead));
} while (bytesRead > 0 && bytes[bytesRead - 1] != 0x04);
completeMessage = completeMessage.Replace(@"”", "");
string datetime = DateTime.Now.ToString();
var x = datetime.Replace(".", string.Empty).Replace(":", string.Empty).Replace(" ", string.Empty);
var inputfilename = "Racun" + x + ".txt";
StreamWriter sws = File.CreateText(inputfilename);
sws.WriteLine(completeMessage);
sws.Close();
string data = completeMessage.ToString();
char[] delimiters = { '\r', '\n' };
string[] invoices = data.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
foreach (var t in invoices)
{
SaveToDataBase(t);
}
var ResponseFile = ResponseClientFolder + "\\" + ResponseClientFileName + x + ".txt";
StreamWriter sw = File.CreateText(ResponseFile);
sw.WriteLine(_odgovor);
sw.Close();
_odgovor = string.Empty;
SendToClient(ResponseFile);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, @"Proces client");
}
}
private void SendToClient(string ResponseFile)
{
try
{
byte[] byteData = File.ReadAllBytes(ResponseFile);
List<byte> byteDat = new List<byte>();
byteDat.AddRange(byteData);
byteDat.Add(0x04);
byteData = byteDat.ToArray();
networkStream.Write(byteData, 0, byteData.Length);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, @"Send to client");
}
}