我之前问过类似的问题,但我似乎无法找到解决方法。我了解通过 TCP 发送数据存在问题,因为某些数据可能会丢失,并且某些数据可能会作为最后一条消息的一部分出现。我正在尝试修复它们,因为我正在从列表中发送一组命令。
这是我的客户发送代码:
private void sendBtn_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < listORequestedCommands.Items.Count; i++)
{
clientSock.Send(Encoding.Default.GetBytes(listORequestedCommands.Items[i].ToString()), listORequestedCommands.Items[i].ToString().Length, SocketFlags.None);
}
removeAll_Click(sender, e);
sendBtn.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!");
this.Close();
}
}
这是我的接收服务器代码:
private void clientReceived(Client sender, byte[] data)
{
try
{
Invoke((MethodInvoker)delegate
{
for (int i = 0; i < lstClients.Items.Count; i++)
{
Client client = lstClients.Items[i].Tag as Client;
if (client.ID == sender.ID)
{
string incommingCommand = Encoding.Default.GetString(data);
if (incommingCommand.CompareTo("") != 0)
{
lstClients.Items[i].SubItems[1].Text = incommingCommand;
string[] splittedIncommingCommand = incommingCommand.Split(' ');
int numRunProc = 0;
do
{
numRunProc = countProcesses();
}
while ((numRunProc >= maxProcesses) || (numRunProc + Int32.Parse(splittedIncommingCommand[splittedIncommingCommand.Length - 1]) >= maxProcesses));
Process processToRun = new Process();
processToRun.StartInfo.FileName = splittedIncommingCommand[0];
processToRun.StartInfo.WorkingDirectory = Path.GetDirectoryName(splittedIncommingCommand[0]);
processToRun.StartInfo.Arguments = "";
for (int j = 1; j < splittedIncommingCommand.Length; j++)
{
processToRun.StartInfo.Arguments += " " + splittedIncommingCommand[j];
}
processToRun.Start();
}
break;
}
}
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!");
this.Close();
}
}
我被指示使用大小前缀和序列化做一些事情,但我遇到了麻烦,似乎无法让它工作。