1.多用panel 让界面美观 重点:dock属性
2.多用try{}catch() {}对会返回异常的函数捕获错误。
3.日志记录(重要)
4.开启监听端口和监听线程:该线程执行StartListen()函数
<span style="white-space:pre"> </span> MyListener = new TcpListener(port);MyListener.Start();Thread th = new Thread(new ThreadStart(StartListen));th.IsBackground = true;th.Start();txtShow.AppendText("监听开始" + "\r\n");
5.接受套接字的连接: Socket sokConnection = MyListener.AcceptSocket();
6.数据库操作:用适配器得到查询的返回数据
<span style="white-space:pre"> </span>static string sqldatabase = @"Server =.;Database = MyCook;Integrated Security=True";/// <summary>/// 处理数据库更新,插入,删除操作,返回受影响行数/// </summary>/// <param name="database"></param>/// <param name="sqltxt"></param>/// <param name="myparas"></param>/// <returns></returns>public static int MyHandleUpdateSql(string sqltxt, params SqlParameter[] myparas){SqlConnection mycon = new SqlConnection(sqldatabase);SqlCommand cmd = new SqlCommand(sqltxt, mycon);if (myparas.Length > 0 && myparas != null){cmd.Parameters.AddRange(myparas);}mycon.Open();int res = -1;res = cmd.ExecuteNonQuery();mycon.Close();return res;}/// <summary>/// 处理数据库查询操作,有返回数据/// </summary>/// <param name="database"></param>/// <param name="sqltxt"></param>/// <param name="myparas"></param>/// <returns></returns>public static DataTable MyHandleSelectSql(string sqltxt, params SqlParameter[] myparas){SqlConnection mycon = new SqlConnection(sqldatabase);SqlCommand cmd = new SqlCommand(sqltxt, mycon);if (myparas.Length > 0 && myparas != null){cmd.Parameters.AddRange(myparas);}SqlDataAdapter da = new SqlDataAdapter(cmd);DataTable dt = new DataTable();da.Fill(dt);// mycon.Close();return dt;}
7.带参数的SQL语句:
<span style="white-space:pre"> </span>string strSql = "update MyCookData set SendFlg=1 where DeviceID=@deviceid";
<span style="white-space:pre"> </span>SqlParameter para = new SqlParameter("@deviceid", deviceid);