只作為個人學習筆記。 ...
只作為個人學習筆記。
class OpData { // 創建一個和客戶端通信的套接字 Socket socketwatch = null; //連接Access字元串 string strCon; OleDbConnection myCon; public TcpListener link(NetChgbCientr.Form1.Updata ud) { //定義一個套接字用於監聽客戶端發來的消息,包含三個參數(IP4定址協議,流式連接,Tcp協議) socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //服務端發送信息需要一個IP地址和埠號 IPAddress address = IPAddress.Parse("192.168.1.112"); TcpListener tls = new TcpListener(address, 8550); tls.Start(); Connect(); //連接資料庫 ud("服務已啟動!\n"); return tls; } //服務啟動 - - 連接資料庫 public void Connect() { strCon = @"Provider = Microsoft.Jet.OLEDB.4.0;Data Source = D:\project\NEWPROJECT\NetChgbServer\bin\Debug\Data2.mdb"; //地址改為全路徑 //實例化連接資料庫對象 myCon = new OleDbConnection(strCon); //開啟連接 myCon.Open(); } //查詢全部數據json格式傳個客戶端 public DataSet Query(String strCom) { // String strCom = "SELECT * FROM CHGB"; //實例化數據集 DataSet myDataSet = new DataSet(); OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myCon); myCommand.Fill(myDataSet, "CHGB"); if (myDataSet != null && myDataSet.Tables.Count > 0)//判斷得到的是不是null或沒有數據的 { return myDataSet; } else { DataSet DS = new DataSet(); return DS; } } }
//業務邏輯 class BllData { TcpListener tls; // 創建一個和客戶端通信的套接字 Socket socketwatch = null; OpData Od = new OpData(); Dictionary<string, Socket> clientConnectionItems = new Dictionary<string, Socket> { }; //啟動伺服器 public void Open(NetChgbCientr.Form1.Updata ud) { tls = Od.link(ud); //負責監聽客戶端的線程:創建一個監聽線程 Thread threadwatch = new Thread(watchconnecting); threadwatch.IsBackground = true; //啟動線程 threadwatch.Start(ud); } //查詢全部數據--json轉換 public void QueryAll() { DataSet ds = new DataSet(); List<CHGB> lis = new List<CHGB>(); String strCom = "SELECT * FROM CHGB"; ds = Od.Query(strCom); //返回查詢結果 //判斷是不是空數據 if (ds == null || ds.Tables.Count <= 0 || ds.Tables[0].Rows.Count <= 0) { return; } //有數據繼續往下執行 for (int i = 0; i < ds.Tables.Count; i++) { foreach (DataRow dts in ds.Tables[i].Rows) { CHGB ch = new CHGB(); ch.JH1 = dts[0].ToString(); ch.QSJS1 = dts[1].ToString(); ch.ZZJS1 = dts[2].ToString(); ch.HD1 = dts[3].ToString(); ch.SB1 = dts[4].ToString(); ch.SND1 = dts[5].ToString(); ch.CZ1 = dts[6].ToString(); ch.HD21 = dts[7].ToString(); ch.JSJG1 = dts[8].ToString(); lis.Add(ch); } } string ja = JsonConvert.SerializeObject(lis); //json序列化,直接將取出來的表格拆分成對象存入集合中,在用下麵的方法序列化 this.Send(ja); } //監聽客戶端發來的請求 public void watchconnecting(object ud) { //tcpClient是socket的封裝(tcpclient.client()方法可以得到socket TcpClient remoteClient = null; //持續不斷監聽客戶端發來的請求 while (true) { try { remoteClient = tls.AcceptTcpClient(); } catch (Exception ex) { //提示套接字監聽異常 MessageBox.Show(ex.Message); break; } //獲取客戶端的IP和埠號 IPAddress IP = (remoteClient.Client.RemoteEndPoint as IPEndPoint).Address; int Port = (remoteClient.Client.RemoteEndPoint as IPEndPoint).Port; //讓客戶顯示"連接成功的"的信息 string sendmsg = "連接服務端成功!\r\n" + "本地IP:" + IP + ",本地埠" + Port; byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg); remoteClient.Client.Send(arrSendMsg); //給外面也弄個套接字 socketwatch = remoteClient.Client; //客戶端網路結點號 string remoteEndPoint = remoteClient.Client.RemoteEndPoint.ToString(); //顯示與客戶端連接情況 String str = "成功與" + remoteEndPoint + "客戶端建立連接!\t\n"; //添加客戶端信息 NetChgbCientr.Form1.Updata ifu = (NetChgbCientr.Form1.Updata)ud; ifu(str); clientConnectionItems.Add(remoteEndPoint, remoteClient.Client); //IPEndPoint netpoint = new IPEndPoint(clientIP,clientPort); IPEndPoint netpoint = remoteClient.Client.RemoteEndPoint as IPEndPoint; ArrayList li = new ArrayList(); li.Add(remoteClient.Client); li.Add(ud); //創建一個通信線程 收 ParameterizedThreadStart pts = new ParameterizedThreadStart(recv); Thread thread = new Thread(pts); //設置為後臺線程,隨著主線程退出而退出 thread.IsBackground = true; //啟動線程 thread.Start(li); } } // 接收客戶端發來的信息,客戶端套接字對象 public void recv(object li) { Socket socketServer = (li as ArrayList)[0] as Socket; while (true) { //創建一個記憶體緩衝區,其大小為1024*1024位元組 即1M byte[] arrServerRecMsg = new byte[1024 * 1024]; //將接收到的信息存入到記憶體緩衝區,並返回其位元組數組的長度 try { //獲取長度判斷請求 int length = socketServer.Receive(arrServerRecMsg); switch (length) { case 1: this.QueryAll(); break; case 2: MessageBox.Show("還沒寫 顯示一條"); break; } //將機器接受到的位元組數組轉換為人可以讀懂的字元串 //string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length); //將發送的字元串信息附加到文本框txtMsg上 //NetChgbServer.Form1.Updata inc = (li as ArrayList)[1] as NetChgbServer.Form1.Updata; //inc("客戶端:" + socketServer.RemoteEndPoint + ",time:" + GetCurrentTime() + "\r\n" + strSRecMsg + "\r\n\n"); } catch (Exception ex) { clientConnectionItems.Remove(socketServer.RemoteEndPoint.ToString()); MessageBox.Show("Client Count:" + clientConnectionItems.Count); //提示套接字監聽異常 MessageBox.Show("客戶端" + socketServer.RemoteEndPoint + "已經中斷連接" + "\r\n" + ex.Message + "\r\n" + ex.StackTrace + "\r\n"); //關閉之前accept出來的和客戶端進行通信的套接字 socketServer.Close(); break; } } } //發送消息給客服端 public void Send(String Ja) { //將輸入的內容字元串轉換為機器可以識別的位元組數組 byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(Ja); //調用客戶端套接字發送位元組數組 socketwatch.Send(arrClientSendMsg); } }
public partial class Form1 : Form { public delegate void Updata(string s); ViShow Vs = new ViShow(); public Form1() { InitializeComponent(); }//啟服務 private void Open_Click(object sender, EventArgs e) { Updata ud = new Updata(UpdateLabel2); Vs.ViOpen(ud); } private void text1_TextChanged(object sender, EventArgs e) { } //主線程外訪問控制項 private void UpdateLabel2(String str) { if (text1.InvokeRequired) { // 當一個控制項的InvokeRequired屬性值為真時,說明有一個創建它以外的線程想訪問它 Action<string> actionDelegate = (x) => { text1.AppendText(x.ToString()); }; // 或者 // Action<string> actionDelegate = delegate(string txt) { this.label2.Text = txt; }; text1.Invoke(actionDelegate, str); } else { text1.AppendText(str); } } }
public partial class Form1 : Form { Thread threadclient = null; Socket socketclient = null; int sign; public Form1() { InitializeComponent();; } //DataShow 容器 private void DataShow_CellContentClick(object sender, DataGridViewCellEventArgs e) { } //顯示全部數據按鈕 ShowAll private void button1_Click(object sender, EventArgs e) { sign = 1; //將輸入的內容字元串轉換為機器可以識別的位元組數組 byte[] arrClientSendMsg = Encoding.UTF8.GetBytes("1"); //調用客戶端套接字發送位元組數組 socketclient.Send(arrClientSendMsg); } //連接伺服器 private void butt2_Click(object sender, EventArgs e) { //定義一個套接字監聽 socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //獲取文本框中的IP地址 IPAddress address = IPAddress.Parse("192.168.1.112"); //將獲取的IP地址和埠號綁定在網路節點上 IPEndPoint point = new IPEndPoint(address, 8550); try { //客戶端套接字連接到網路節點上,用的是Connect socketclient.Connect(point); sign = 0; } catch (Exception) { MessageBox.Show("連接失敗\r\n"); return; } threadclient = new Thread(recv); threadclient.IsBackground = true; threadclient.Start(); } // 接收服務端發來信息的方法 void recv() { //持續監聽服務端發來的消息 while (true) { //定義一個1M的記憶體緩衝區,用於臨時性存儲接收到的消息 byte[] arrRecvmsg = new byte[1024 * 1024]; //將客戶端套接字接收到的數據存入記憶體緩衝區,並獲取長度 int length = socketclient.Receive(arrRecvmsg); //將套接字獲取到的字元數組轉換為人可以看懂的字元串 string strRevMsg = Encoding.UTF8.GetString(arrRecvmsg, 0, length);
Control.CheckForIllegalCrossThreadCalls = false; //這裡不允許這樣操作訪問控制項,這裡為了測試方便 if (sign == 0) { MessageBox.Show(strRevMsg); this.butt2.Text = "斷開連接"; sign = 1; } else { MessageBox.Show(strRevMsg); List<CHGB> list = JsonConvert.DeserializeObject<List<CHGB>>(strRevMsg); //先給DataSource 一個地址,再把list給DataGridView控制項 //不給地址會報 ”引用沒有作用到實例上“ DataTable dt = new DataTable(); this.DataShow.DataSource = dt;// list; this.DataShow.DataSource = list; } } }