问题描述
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Diagnostics;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.ComponentModel;usingSystem.Windows.Forms;namespaceDadabaseToExcelTest{classTempSampleInput{privateSockettemperSampleSocket=null;//温度扫描仪套接字privatestringhostName="";//主机IP地址privatestringportNum="";//端口号privateboolthreadRunningFlag=false;//线程运行标志privateGlobalVariant.EFeedbackSignalfeedBackSignal;//信号反馈类型intelapsed=0;//测量时间用intinputPeriod=500;//采样间隔时间publicintSampleCount=0;publicTempSampleInput(){}//初始配置采样函数publicvoidInitialize(){this.hostName="192.168.2.100";this.portNum="5025";this.feedBackSignal=GlobalVariant.FeedbackSignal;//信号采集通道this.threadRunningFlag=true;Threadthread=newThread(newThreadStart(InitializeSocket));thread.IsBackground=true;thread.Start();}//初始化套接字privatevoidInitializeSocket(){try{if(temperSampleSocket==null||temperSampleSocket.Connected==false){IPEndPointipe=newIPEndPoint(IPAddress.Parse(hostName),int.Parse(portNum));SockettempSocket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);//创建Socket新实例tempSocket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,5000);//设置Socket连接超时为5秒tempSocket.Connect(ipe);//尝试套接字连接if(tempSocket.Connected){temperSampleSocket=tempSocket;TempInputProc();}}else{if(temperSampleSocket.Connected==true)//若套接字已连接上,则继续采集{TempInputProc();}}}catch(System.Net.Sockets.SocketExceptionsEx){Trace.WriteLine("SocketExceptionInTemperatureSampleInput.InitializeSocket:"+sEx.Message);stringsMessage=trimMessage(sEx.Message,20,'n');MessageBox.Show(sMessage,"1586ALAN端口异常",MessageBoxButtons.OK,MessageBoxIcon.Warning);}catch(Exceptionex){Trace.WriteLine("UnexpectedexceptioninTemperatureSampleInput.InitializeSocket:"+ex.Message);}}//温度采集函数privatevoidTempInputProc(){StopwatchswReturnTime=newStopwatch();Parse(temperSampleSocket,"ROUT:SCAN(@3,4)"//扫描路径Trace.WriteLine("扫描路径设置");Parse(temperSampleSocket,"INIT:CONT1");//测试中,应根据测试用传感器进行温度扫描仪配置Trace.WriteLine("启动扫描");//Thread.Sleep(2000);//此处挂起三秒?while(threadRunningFlag){swReturnTime.Reset();swReturnTime.Start();Trace.WriteLine("开始读取数据");//Parse(temperSampleSocket,)stringstr=Parse(temperSampleSocket,"FETCH?");string[]arrayStr=str.Split(',');//按逗号将返回的数据组分开//GlobalVariant.TemperatureOutputData[0]=GlobalVariant.TemperatureOutputData[1]=//GlobalVariant.TemperatureOutputData[2]=GlobalVariant.TemperatureOutputData[3]=0;//初始化采集数据,0表示未采集数据if(arrayStr[1]=="C")//如果返回的第二个数为C,表示摄氏度,代表已采到数据,根据返回的第三个数即通道数来对应赋值。{switch(arrayStr[2]){case"1":{GlobalVariant.TemperatureOutputData[0]=Convert.ToDouble(arrayStr[0]);break;}case"2":{GlobalVariant.TemperatureOutputData[1]=Convert.ToDouble(arrayStr[0]);break;}case"3":{GlobalVariant.TemperatureOutputData[2]=Convert.ToDouble(arrayStr[0]);break;}case"4":{GlobalVariant.TemperatureOutputData[3]=Convert.ToDouble(arrayStr[0]);break;}default:{break;}}}Trace.WriteLine("通道1数据"+GlobalVariant.TemperatureOutputData[0]+"n"+"通道2数据"+GlobalVariant.TemperatureOutputData[1]+"n"+"通道3数据"+GlobalVariant.TemperatureOutputData[2]+"n"+"通道4数据"+GlobalVariant.TemperatureOutputData[3]);swReturnTime.Stop();elapsed=(int)swReturnTime.ElapsedMilliseconds;stringnowTime=GetCurrentTime();Trace.WriteLine("CurrentTime:"+nowTime+",WaitTime:"+elapsed+","+str);dataFlag=true;}Parse(temperSampleSocket,"INIT:CONT0");//停止扫描temperSampleSocket.Close();}//Socket发送指令privatestringParse(SockettemperSampleSocket,stringcommand){try{Trace.WriteLine("表示已连接上");Byte[]data=System.Text.Encoding.ASCII.GetBytes(command);//转换为ASCII码temperSampleSocket.Send(data);//发送命令Byte[]endCRLF={(Byte)'r',(Byte)'n'};//终止命令temperSampleSocket.Send(endCRLF);//发送终止命令Trace.WriteLine("发送终结指令一次");//测试用if(command.IndexOf("?")>=0){for(inti=0;i<20;i++)Thread.Sleep(inputPeriod);returnresponse(temperSampleSocket);}if(command.IndexOf("0")>=0){temperSampleSocket.Close();}return"";}catch(System.Net.Sockets.SocketExceptionsEx){Trace.WriteLine("SocketExceptionInTemperatureSampleInput.Parse:"+sEx.Message);return"";}catch(Exceptionex){Trace.WriteLine("UnexpectedexceptionInTemperatureSampleInput.Parse:"+ex.Message);return"";}}privatestringresponse(Socketclient){try{Byte[]data=newByte[512];//缓冲区大小stringresponseData="";intbyteCount=0;do{//将client返回的数据存入缓冲区,如果没有可读取的数据,//则Receive方法将一直处于阻止状态,直到数据可用,返回值为接受的字节数byteCount=client.Receive(data);responseData+=System.Text.Encoding.ASCII.GetString(data,0,byteCount);//将字节数组中某个范围的字节解码为一个字符串}while(responseData.IndexOf('n')<0);//如果没收到CRLF,表示回复还没有结束,应继续等待Trace.WriteLine("responseData:"+responseData);returnresponseData;}catch(System.Net.Sockets.SocketExceptionsEx){Trace.WriteLine("SocketExceptionInTemperatureSampleInput.response:"+sEx.Message);return"";}catch(Exceptionex){Trace.WriteLine("UnexpectedexceptionInTemperatureSampleInput.response:"+ex.Message);return"";}}}在System.Net.Sockets.SocketException中第一次偶然出现的“System.dll”类型的异常SocketExceptionInTemperatureSampleInput.response:由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。“DatabaseToExcelTest.vshost.exe”(托管(v4.0.30319)):已加载“C:WINDOWSMicrosoft.NetassemblyGAC_MSILmscorlib.resourcesv4.0_4.0.0.0_zh-Hans_b77a5c561934e089mscorlib.resources.dll”在System.IndexOutOfRangeException中第一次偶然出现的“DatabaseToExcelTest.exe”类型的异常UnexpectedexceptioninTemperatureSampleInput.InitializeSocket:索引超出了数组界限。第一次尝试连接设备,会报以上错误,但重启程序,运行通过,求大神指导
解决方案
解决方案二:
仅仅是一个连接错误结果你却把你的全部代码放了上来而且还是没有放在这个里面的
谁愿意来看啊如果是连接不上什么的就去看看你的Connect方法到底是怎么回事学会排查问题去找到报出你上面错误的具体代码是在哪一行然后去看看那一行到底在做什么传入的是什么样的数据
解决方案三:
看是在哪儿报的数组越界,估计是传入了空值之类的吧