我用socket连接通信,长连接,然后建立一个线程不停接收,为什么一段时间后就节后不大准确的数据,能接收到数据,但是处理时有问题,是不是不能这样做?有什么办法可以解决吗?有什么更好的办法吗?求指导,非常感谢!!!下面是代码:
连接:
private void button1_Click(object sender, EventArgs e)
{
IPAddress Ips1 = IPAddress.Parse("192.168.137.101");
IPEndPoint Ip1 = new IPEndPoint(Ips1, Convert.ToInt32("2001"));
s1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
s1.Connect(Ip1);
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
return;
}
MessageBox.Show("1连接成功");
Thread threadRec1 = new Thread(Receive1);
threadRec1.IsBackground = true;
threadRec1.Start();
}
接收:private void Receive1()
{
while (true)
{
byte[] buf1 = new byte[1024 * 1024 * 2];
s1.Receive(buf1);
textBox9.AppendText(Encoding.ASCII.GetString(buf1) + "rn");
if ((buf1[0] == 'x') && (buf1[6] == 'y'))
{
NA1 = (Convert.ToInt32(buf1[1]) - 48) * 100 + (Convert.ToInt32(buf1[2]) - 48) * 10 + (Convert.ToInt32(buf1[3]) - 48);
textBox15.Text = Convert.ToString(NA1);
ND1 = (Convert.ToInt32(buf1[4]) - 48) * 10 + (Convert.ToInt32(buf1[5]) - 48);
textBox11.Text = Convert.ToString(ND1);
SD1 = SD1 + ND1;
textBox13.Text = Convert.ToString(SD1);
Thread.Sleep(470);
}
}
}
|