2017.8.2
服务器:
1 #region 参数与集合 2 /// <summary> 3 /// 客户端IP 4 /// </summary> 5 string clientIP; 6 /// <summary> 7 /// IP地址(IPAddress) 8 /// </summary> 9 string thisIp; 10 /// <summary> 11 /// 端口(Port) 12 /// </summary> 13 int port; 14 /// <summary> 15 /// Thread:监听客户端连接请求 16 /// </summary> 17 Thread watchClientThread = null; 18 /// <summary> 19 /// Socket:监听客户端连接请求 20 /// </summary> 21 Socket watchClientSocker = null; 22 /// <summary> 23 /// 套接字集合(Socket Gether) 24 /// </summary> 25 Dictionary<string, Socket> dictSocket = new Dictionary<string, Socket>(); 26 /// <summary> 27 /// 线程集合(Thread Gether) 28 /// </summary> 29 Dictionary<string, Thread> dictThread = new Dictionary<string, Thread>(); 30 #endregion 31 32 #region 获取本地IP地址 33 /// <summary> 34 /// 获取本地IP地址 35 /// </summary> 36 private void GetIPAddress() 37 { 38 NetworkInterface[] nis = NetworkInterface.GetAllNetworkInterfaces(); 39 if (nis.Length > 0) 40 { 41 for (int i = 0; i < nis.Length; i++) 42 { 43 foreach (var item in nis[i].GetIPProperties().UnicastAddresses) 44 { 45 string s = item.Address.ToString(); 46 string[] ss = s.Split('.'); 47 if (ss.Length == 4) 48 { 49 if (ss[0].ToString() != "127" && ss[0].ToString() == "192") 50 { 51 thisIp = s; 52 break; 53 } 54 } 55 } 56 } 57 } 58 } 59 #endregion 60 61 #region 启动服务器 62 /// <summary> 63 /// 启动服务器 64 /// </summary> 65 public void SocketStart() 66 { 67 GetIPAddress(); 68 port = 8888; 69 watchClientSocker = new Socket(AddressFamily.InterNetwork, 70 SocketType.Stream, 71 ProtocolType.Tcp); 72 IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(thisIp), port); 73 try 74 { 75 watchClientSocker.Bind(endPoint); 76 } 77 catch (SocketException se) 78 { 79 rtbMonitoring.Text += "异常:" + se.Message + " "; 80 return; 81 } 82 catch (Exception ex) 83 { 84 rtbMonitoring.Text += "异常:" + ex.Message + " "; 85 } 86 watchClientSocker.Listen(50); 87 watchClientThread = new Thread(WatchConnection); 88 watchClientThread.IsBackground = true; 89 watchClientThread.Start(); 90 } 91 #endregion 92 93 #region 开始监听客户端连接请求 94 /// <summary> 95 /// 开始监听客户端连接请求 96 /// </summary> 97 void WatchConnection() 98 { 99 while (true) 100 { 101 Socket socketConn = watchClientSocker.Accept(); 102 clientIP = socketConn.RemoteEndPoint.ToString(); 103 dictSocket.Add(clientIP, socketConn); 104 Thread thr = new Thread(ReccptionData); 105 thr.IsBackground = true; 106 thr.Start(socketConn); 107 dictThread.Add(clientIP, thr); 108 rtbMonitoring.Text += clientIP + " 连接成功" + " "; 109 } 110 } 111 #endregion 112 113 #region 客户端信息处理 114 /// <summary> 115 /// 客户端信息处理 116 /// </summary> 117 /// <param name="socketConn"></param> 118 void ReccptionData(object socketConn) 119 { 120 Socket socketClient = socketConn as Socket; 121 while (true) 122 { 123 byte[] arrRec = new byte[1024 * 1024 * 6]; 124 int length = -1; 125 try 126 { 127 length = socketClient.Receive(arrRec); 128 } 129 catch (SocketException se) 130 { 131 rtbMonitoring.Text += "异常:" + se.Message+" "; 132 dictSocket.Remove(socketClient.RemoteEndPoint.ToString()); 133 dictThread.Remove(socketClient.RemoteEndPoint.ToString()); 134 break; 135 } 136 if (arrRec[0] == 0) 137 { 138 clientIP = socketClient.RemoteEndPoint.ToString(); 139 string strMsg = System.Text.Encoding.UTF8.GetString(arrRec, 1, length - 1);// 将接受到的字节数据转化成字符串; 140 ReturnData(strMsg); 141 rtbMonitoring.Text +=clientIP+":"+ strMsg + " "; 142 } 143 if (arrRec[0] == 1) 144 { 145 if (!Directory.Exists("FileInfo")) 146 { 147 Directory.CreateDirectory("FileInfo"); 148 } 149 if (!File.Exists(arrRec + ".txt")) 150 { 151 File.Create(arrRec + ".txt"); 152 } 153 string fileSavePath = arrRec + " .txt"; 154 using (FileStream fs = new FileStream(fileSavePath, FileMode.Create)) 155 { 156 fs.Write(arrRec, 1, length - 1); 157 rtbMonitoring.Text += "文件保存成功:" + fileSavePath + " "; 158 159 } 160 } 161 } 162 163 } 164 #endregion 165 166 #region 返回请求数据 167 /// <summary> 168 /// 返回请求数据 169 /// </summary> 170 /// <param name="data"></param> 171 void ReturnData(string data) 172 { 173 string connectSql = "server=.;database=Thread_SocketDB;uid=sa;pwd=sa;"; 174 string strMsg; 175 UserInfo u = new UserInfo(); 176 GetSql getsql = new GetSql(); 177 List<UserInfo> us = new List<UserInfo>(); 178 string[] datas = data.Split('/'); 179 string operationType = ""; 180 string type = ""; 181 string userName = ""; 182 string pwd = ""; 183 if (datas.Length > 4) 184 { 185 operationType = datas[1]; 186 type = datas[2]; 187 userName = datas[3]; 188 pwd = datas[4]; 189 } 190 switch (operationType) 191 { 192 case "用户": 193 switch (type) 194 { 195 case "登录": 196 SqlConnection con = new SqlConnection(connectSql); 197 con.Open(); 198 SqlCommand com = new SqlCommand(getsql.GetSelectAll(), con); 199 SqlDataReader dr = com.ExecuteReader(); 200 while (dr.Read()) 201 { 202 u = new UserInfo(); 203 u.UserName = dr["UserName"].ToString(); 204 u.Pwd = dr["Pwd"].ToString(); 205 us.Add(u); 206 } 207 dr.Close(); 208 con.Close(); 209 strMsg = "正在验证登录信息..."; 210 SendContent(strMsg); 211 List<UserInfo> loginInfo = us.FindAll((p) => 212 p.UserName == userName); 213 if (loginInfo.Count <= 0) 214 { 215 strMsg = "对不起,你的账号不存在!"; 216 SendContent(strMsg); 217 218 } 219 else 220 { 221 foreach (UserInfo userInfo in loginInfo) 222 { 223 u = userInfo; 224 } 225 226 if (pwd != u.Pwd) 227 { 228 229 strMsg = "对不起,你的密码不正确!"; 230 SendContent(strMsg); 231 232 } 233 else 234 { 235 strMsg = "登录成功!"; 236 SendContent(strMsg); 237 } 238 } 239 break; 240 case "编号查询": 241 242 break; 243 } 244 break; 245 case "管理员": 246 247 break; 248 } 249 } 250 #endregion 251 252 #region 封装发送信息 253 /// <summary> 254 /// 封装发送信息 255 /// </summary> 256 /// <param name="strMsg"></param> 257 private void SendContent(string s) 258 { 259 byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(s); 260 byte[] arrSendMsg = new byte[arrMsg.Length + 1]; 261 arrSendMsg[0] = 0; // 用来表示发送的是消息数据 262 Buffer.BlockCopy(arrMsg, 0, arrSendMsg, 1, arrMsg.Length); 263 dictSocket[clientIP].Send(arrSendMsg); 264 } 265 #endregion
客户端:
1 /// <summary> 2 /// 客户端套接字对象 3 /// </summary> 4 Socket sockClient = null; 5 /// <summary> 6 /// 客户端线程 7 /// </summary> 8 Thread threadCilent = null; 9 #region 开始连接字符串 10 /// <summary> 11 /// 开始连接字符串 12 /// </summary> 13 public void ServerConnect() 14 { 15 try 16 { 17 IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.4.186"), 8888); 18 sockClient = new Socket(AddressFamily.InterNetwork, 19 SocketType.Stream, 20 ProtocolType.Tcp); 21 try 22 { 23 lbReception.Text = "正在与服务器进行连接... "; 24 sockClient.Connect(endPoint); 25 } 26 catch (SocketException se) 27 { 28 lbReception.Text = "异常:" + se.Message + " "; 29 return; 30 } 31 lbReception.Text = "连接成功!"; 32 threadCilent = new Thread(Res); 33 threadCilent.IsBackground = true; 34 threadCilent.Start(); 35 36 } 37 catch (Exception) 38 { 39 lbReception.Text = "IP无效!"; 40 throw; 41 } 42 43 44 } 45 46 #region 接收数据处理 47 /// <summary> 48 /// 接收数据处理 49 /// </summary> 50 private void Res() 51 { 52 53 while (true) 54 { 55 // 定义一个2M的缓存区; 56 byte[] arrMsgRec = new byte[1024 * 1024 * 6]; 57 // 将接受到的数据存入到输入 arrMsgRec中; 58 int length = -1; 59 try 60 { 61 length = sockClient.Receive(arrMsgRec); // 接收数据,并返回数据的长度; 62 } 63 catch (SocketException se) 64 { 65 lbReception.Text = "异常;" + se.Message; 66 return; 67 } 68 catch (Exception e) 69 { 70 lbReception.Text = "异常:" + e.Message; 71 return; 72 } 73 if (arrMsgRec[0] == 0) // 表示接收到的是消息数据; 74 { 75 string strMsg = System.Text.Encoding.UTF8.GetString(arrMsgRec, 1, length - 1);// 将接受到的字节数据转化成字符串; 76 lbReception.Text = strMsg; 77 } 78 } 79 } 80 #endregion 81 #endregion 82 83 #region 发送数据 84 /// <summary> 85 /// 发送数据 86 /// </summary> 87 /// <param name="s"></param> 88 public void send(string s) 89 { 90 try 91 { 92 byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(s); 93 byte[] arrSendMsg = new byte[arrMsg.Length + 1]; 94 arrSendMsg[0] = 0; // 用来表示发送的是消息数据 95 Buffer.BlockCopy(arrMsg, 0, arrSendMsg, 1, arrMsg.Length); 96 sockClient.Send(arrSendMsg); // 发送消息; 97 } 98 catch (Exception) 99 { 100 101 throw; 102 } 103 104 } 105 #endregion