SOCKET数据传输用字符串加结束符比较简单,对于不同平台的客户端,也都用这种通用的方法简单一点。
服务器端影子对象类
public class ClientInfo
{
public IntPtr ConnId { get; set; }
public string IpAddress { get; set; }
public ushort Port { get; set; }
public long Sends { get; set; }
public long Receives { get; set; }
public string User { get; set; }
public string Logontime { get; set; }
public string Rtxt { get; set; }
public string Stxt { get; set; }
public List<string[]> CommandArray { get; set; }
public ClientInfo()
{
CommandArray = new List<string[]>();
}
//--------分割函数,把长字符串解析到command-------
public void RtxtCut()
{
while (Rtxt.IndexOf('.') > 0)
{
//取"."前的字符串,按"|"分割
string tmp = Rtxt.Substring(0, Rtxt.IndexOf('.'));
string[] ss = tmp.Split('|').Where(s => !string.IsNullOrEmpty(s)).ToArray();
CommandArray.Add(ss);
//取"."前的字符串,也包含"." 上面取后删除掉!
Rtxt = Rtxt.Substring(Rtxt.IndexOf('.') + 1);
}
}
public string PrintFirstCommand()
{
string tmp = "";
foreach (string one in CommandArray.ElementAt(0))
{
tmp = tmp + " " + one;
}
return tmp;
}
}
//------------SOCKET单次数据结构-----------
1|user1|123456.
5|L3AKFEM3XHY301592|AFI08L.
其中: .(结束) |(数据分割 )
//------------数据存储对象-------------
public List<string[]> CommandArray { get; set; }
这是一个字符串数组对象,正好把单次数据,分割放入一个字符串数组中,
每次数据到达,先读 . 结束符前面全部数据,然后按 | 把前面全部数据分割,
RtxtCut() 工作会连续切割字符串,把每一个 . 结束符前的字符串压入list中。
//-----------SOCKET单次发表数据------------
有很多场景,单次要求发送数据是一个表,不止是几个变量,
这时在单个变量中,再设置分隔符号和结束符号,用来表示表数据,
105|10005333-物料1-1,10004059-物料2-1,.
其中: . (结束) | (数据分割 )
表数据中: ,(结束) - (数据分割 )
处理代码:
string[] tab = s[1].Split(',');
for (int i = 0; i < tab.Count(); i++)
{
string[] row = tab[i].Split('-');
}