我之前问过类似的问题,但我似乎无法找到一种方法来做到这一点。 我知道在通过TCP发送数据时存在问题,因为有些数据可能会丢失,有些数据可能会成为最后一条消息的一部分。 我试图解决它们,因为我从列表发送一组命令。通过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();
}
}
我奉命做一些与大小前缀和系列化,但我遇到了麻烦,似乎无法让它工作。
您是否有兴趣了解底层结构或只是针对您的问题的工作解决方案? – MarcF
您对TCP的理解不正确:TCP确保按顺序传递数据包,而不会丢失数据包。详情请参阅http://en.wikipedia.org/wiki/Transmission_Control_Protocol。 –
实际上我对这两个都很感兴趣,现在我只需要一个解决方案,因为我需要发布一个版本。但是,我也想了解它以备将来使用。谢谢。 – Idanis