frmClient.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using HPSocketCS;
  10. using System.Runtime.InteropServices;
  11. using System.IO;
  12. using System.Threading;
  13. namespace SSLClientNS
  14. {
  15. public enum AppState
  16. {
  17. Starting, Started, Stoping, Stoped, Error
  18. }
  19. public enum StudentType
  20. {
  21. None, Array, List, Single,
  22. }
  23. public partial class frmClient : Form
  24. {
  25. private AppState appState = AppState.Stoped;
  26. private delegate void ConnectUpdateUiDelegate();
  27. private delegate void SetAppStateDelegate(AppState state);
  28. private delegate void ShowMsg(string msg);
  29. private ShowMsg AddMsgDelegate;
  30. HPSocketCS.SSLClient client = null;
  31. bool isSendFile = false;
  32. StudentType studentType = StudentType.None;
  33. public frmClient()
  34. {
  35. InitializeComponent();
  36. }
  37. private void frmClient_Load(object sender, EventArgs e)
  38. {
  39. try
  40. {
  41. client = new HPSocketCS.SSLClient();
  42. client.VerifyMode = SSLVerifyMode.Peer | SSLVerifyMode.FailIfNoPeerCert;
  43. client.CAPemCertFileOrPath = "ssl-cert\\ca.crt";
  44. client.PemCertFile = "ssl-cert\\server.cer";
  45. client.PemKeyFile = "ssl-cert\\server.key";
  46. client.KeyPasswod = "123456";
  47. // 加个委托显示msg,因为on系列都是在工作线程中调用的,ui不允许直接操作
  48. AddMsgDelegate = new ShowMsg(AddMsg);
  49. // 设置client事件
  50. client.OnPrepareConnect += new TcpClientEvent.OnPrepareConnectEventHandler(OnPrepareConnect);
  51. client.OnConnect += new TcpClientEvent.OnConnectEventHandler(OnConnect);
  52. client.OnSend += new TcpClientEvent.OnSendEventHandler(OnSend);
  53. client.OnReceive += new TcpClientEvent.OnReceiveEventHandler(OnReceive);
  54. client.OnClose += new TcpClientEvent.OnCloseEventHandler(OnClose);
  55. client.OnHandShake += new SSLClientEvent.OnHandShakeEventHandler(OnHandShake);
  56. SetAppState(AppState.Stoped);
  57. }
  58. catch (Exception ex)
  59. {
  60. SetAppState(AppState.Error);
  61. AddMsg(ex.Message);
  62. }
  63. }
  64. private void btnStart_Click(object sender, EventArgs e)
  65. {
  66. try
  67. {
  68. String ip = this.txtIpAddress.Text.Trim();
  69. ushort port = ushort.Parse(this.txtPort.Text.Trim());
  70. // 写在这个位置是上面可能会异常
  71. SetAppState(AppState.Starting);
  72. AddMsg(string.Format("$Client Starting ... -> ({0}:{1})", ip, port));
  73. if (client.Connect(ip, port, this.cbxAsyncConn.Checked))
  74. {
  75. if (cbxAsyncConn.Checked == false)
  76. {
  77. SetAppState(AppState.Started);
  78. }
  79. AddMsg(string.Format("$Client Start OK -> ({0}:{1})", ip, port));
  80. }
  81. else
  82. {
  83. SetAppState(AppState.Stoped);
  84. throw new Exception(string.Format("$Client Start Error -> {0}({1})", client.ErrorMessage, client.ErrorCode));
  85. }
  86. }
  87. catch (Exception ex)
  88. {
  89. AddMsg(ex.Message);
  90. }
  91. }
  92. private void btnStop_Click(object sender, EventArgs e)
  93. {
  94. // 停止服务
  95. AddMsg("$Server Stop");
  96. if (client.Stop())
  97. {
  98. SetAppState(AppState.Stoped);
  99. }
  100. else
  101. {
  102. AddMsg(string.Format("$Stop Error -> {0}({1})", client.ErrorMessage, client.ErrorCode));
  103. }
  104. }
  105. private void btnSend_Click(object sender, EventArgs e)
  106. {
  107. try
  108. {
  109. string send = this.txtSend.Text;
  110. if (send.Length == 0)
  111. {
  112. return;
  113. }
  114. byte[] bytes = Encoding.Default.GetBytes(send);
  115. IntPtr connId = client.ConnectionId;
  116. // 发送
  117. if (client.Send(bytes, bytes.Length))
  118. {
  119. AddMsg(string.Format("$ ({0}) Send OK --> {1}", connId, send));
  120. }
  121. else
  122. {
  123. AddMsg(string.Format("$ ({0}) Send Fail --> {1} ({2})", connId, send, bytes.Length));
  124. }
  125. }
  126. catch (Exception ex)
  127. {
  128. AddMsg(string.Format("$ Send Fail --> msg ({0})", ex.Message));
  129. }
  130. }
  131. private void btnSendSerializableObject_Click(object sender, EventArgs e)
  132. {
  133. try
  134. {
  135. // 注: 对象序列化发送数据较大
  136. if (studentType != StudentType.None)
  137. {
  138. // 正在执行
  139. throw new Exception("being implemented");
  140. }
  141. IntPtr connId = client.ConnectionId;
  142. Thread thread = new Thread(new ThreadStart(delegate()
  143. {
  144. Student[] students = new Student[2];
  145. students[0] = new Student();
  146. students[0].Id = 1;
  147. students[0].Name = "张三";
  148. students[0].Sex = Sex.Female;
  149. students[1] = new Student();
  150. students[1].Id = 2;
  151. students[1].Name = "李四";
  152. students[1].Sex = Sex.Male;
  153. // 发送数组对象
  154. studentType = StudentType.Array;
  155. if (client.SendBySerializable(students))
  156. {
  157. AddMsg(string.Format("$ ({0}) Send OK --> {1}", connId, "Student[]"));
  158. }
  159. else
  160. {
  161. AddMsg(string.Format("$ ({0}) Send Fail --> {1}", connId, "Student[]"));
  162. }
  163. ////////////////////////////////////////////////////////////////////////////////
  164. // 改变性别
  165. students[0].Sex = Sex.Transsexual;
  166. List<Student> stuList = new List<Student>();
  167. stuList.Add(students[0]);
  168. stuList.Add(students[1]);
  169. // 防止粘包,延迟2秒发送下一组数据
  170. AddMsg(" *** 2 seconds after sending ...");
  171. Thread.Sleep(2000);
  172. // 发送list对象
  173. studentType = StudentType.List;
  174. if (client.SendBySerializable(stuList))
  175. {
  176. AddMsg(string.Format("$ ({0}) Send OK --> {1}", connId, "List<Student>"));
  177. }
  178. else
  179. {
  180. AddMsg(string.Format("$ ({0}) Send Fail --> {1}", connId, "List<Student>"));
  181. }
  182. ////////////////////////////////////////////////////////////////////////////////
  183. // 防止粘包,延迟2秒发送下一组数据
  184. AddMsg(" *** 2 seconds after sending ...");
  185. Thread.Sleep(2000);
  186. // 改变性别
  187. students[0].Sex = Sex.Unknown;
  188. // 发送单个学员信息
  189. studentType = StudentType.Single;
  190. if (client.SendBySerializable(students[0]))
  191. {
  192. AddMsg(string.Format("$ ({0}) Send OK --> {1}", connId, "Student"));
  193. }
  194. else
  195. {
  196. AddMsg(string.Format("$ ({0}) Send Fail --> {1}", connId, "Student"));
  197. }
  198. }));
  199. thread.Start();
  200. }
  201. catch (Exception ex)
  202. {
  203. studentType = StudentType.None;
  204. AddMsg(string.Format("$ Send Fail --> msg ({0})", ex.Message));
  205. }
  206. }
  207. private void lbxMsg_KeyPress(object sender, KeyPressEventArgs e)
  208. {
  209. // 清理listbox
  210. if (e.KeyChar == 'c' || e.KeyChar == 'C')
  211. {
  212. this.lbxMsg.Items.Clear();
  213. }
  214. }
  215. void ConnectUpdateUi()
  216. {
  217. if (this.cbxAsyncConn.Checked == true)
  218. {
  219. SetAppState(AppState.Started);
  220. }
  221. }
  222. private bool SendFileToServer(string filePath)
  223. {
  224. FileInfo fi = new FileInfo(filePath);
  225. if (fi.Length > 4096 * 1024)
  226. {
  227. throw new Exception("被发送文件大小不能超过4096KB。");
  228. }
  229. else if (fi.Length == 0)
  230. {
  231. throw new Exception("文件大小不能为0。");
  232. }
  233. // 头附加数据
  234. MyFileInfo myFile = new MyFileInfo()
  235. {
  236. FilePath = filePath,
  237. FileSize = fi.Length,
  238. };
  239. // 发送文件标记,用来在onrecv里判断是否文件回包
  240. isSendFile = true;
  241. // 不附加尾数据
  242. bool ret = client.SendSmallFile<MyFileInfo, object>(filePath, myFile, null);
  243. if (ret == false)
  244. {
  245. isSendFile = false;
  246. int error = client.SYSGetLastError();
  247. AddMsg(string.Format(" > [SendSmallFile] errorCode:{0}", error));
  248. }
  249. return ret;
  250. }
  251. HandleResult OnPrepareConnect(TcpClient sender, uint socket)
  252. {
  253. return HandleResult.Ok;
  254. }
  255. HandleResult OnConnect(TcpClient sender)
  256. {
  257. // 已连接 到达一次
  258. // 如果是异步联接,更新界面状态
  259. this.Invoke(new ConnectUpdateUiDelegate(ConnectUpdateUi));
  260. AddMsg(string.Format(" > [{0},OnConnect]", sender.ConnectionId));
  261. return HandleResult.Ok;
  262. }
  263. HandleResult OnSend(TcpClient sender, byte[] bytes)
  264. {
  265. // 客户端发数据了
  266. AddMsg(string.Format(" > [{0},OnSend] -> ({1} bytes)", sender.ConnectionId, bytes.Length));
  267. return HandleResult.Ok;
  268. }
  269. HandleResult OnReceive(TcpClient sender, byte[] bytes)
  270. {
  271. // 数据到达了
  272. if (isSendFile == true)
  273. {
  274. // 如果发送了文件,并接收到了返回数据
  275. isSendFile = false;
  276. MyFileInfo myFile = client.BytesToStruct<MyFileInfo>(bytes);
  277. int objSize = Marshal.SizeOf(myFile);
  278. // 因为没有附加尾数据,所以大小可以用length - objSize
  279. byte[] contentBytes = new byte[bytes.Length - objSize];
  280. Array.ConstrainedCopy(bytes, objSize, contentBytes, 0, contentBytes.Length);
  281. string txt = Encoding.Default.GetString(contentBytes);
  282. string msg = string.Empty;
  283. if (txt.Length > 100)
  284. {
  285. msg = txt.Substring(0, 100) + "......";
  286. }
  287. else
  288. {
  289. msg = txt;
  290. }
  291. AddMsg(string.Format(" > [{0},OnReceive] -> FileInfo(Path:\"{1}\",Size:{2})", sender.ConnectionId, myFile.FilePath, myFile.FileSize));
  292. AddMsg(string.Format(" > [{0},OnReceive] -> FileContent(\"{1}\")", sender.ConnectionId, msg));
  293. }
  294. else if (studentType != StudentType.None)
  295. {
  296. switch (studentType)
  297. {
  298. case StudentType.Array:
  299. Student[] students = sender.BytesToObject(bytes) as Student[];
  300. foreach (var stu in students)
  301. {
  302. AddMsg(string.Format(" > [{0},OnReceive] -> Student({1},{2},{3})", sender.ConnectionId, stu.Id, stu.Name, stu.GetSexString()));
  303. }
  304. break;
  305. case StudentType.List:
  306. List<Student> stuList = sender.BytesToObject(bytes) as List<Student>;
  307. foreach (var stu in stuList)
  308. {
  309. AddMsg(string.Format(" > [{0},OnReceive] -> Student({1},{2},{3})", sender.ConnectionId, stu.Id, stu.Name, stu.GetSexString()));
  310. }
  311. break;
  312. case StudentType.Single:
  313. Student student = sender.BytesToObject(bytes) as Student;
  314. AddMsg(string.Format(" > [{0},OnReceive] -> Student({1},{2},{3})", sender.ConnectionId, student.Id, student.Name, student.GetSexString()));
  315. studentType = StudentType.None;
  316. break;
  317. }
  318. }
  319. else
  320. {
  321. AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)", sender.ConnectionId, bytes.Length));
  322. }
  323. return HandleResult.Ok;
  324. }
  325. HandleResult OnClose(TcpClient sender, SocketOperation enOperation, int errorCode)
  326. {
  327. if(errorCode == 0)
  328. // 连接关闭了
  329. AddMsg(string.Format(" > [{0},OnClose]", sender.ConnectionId));
  330. else
  331. // 出错了
  332. AddMsg(string.Format(" > [{0},OnError] -> OP:{1},CODE:{2}", sender.ConnectionId, enOperation, errorCode));
  333. // 通知界面,只处理了连接错误,也没进行是不是连接错误的判断,所以有错误就会设置界面
  334. // 生产环境请自己控制
  335. this.Invoke(new SetAppStateDelegate(SetAppState), AppState.Stoped);
  336. return HandleResult.Ok;
  337. }
  338. HandleResult OnHandShake(TcpClient sender)
  339. {
  340. // ssl握手了
  341. AddMsg(string.Format(" > [{0},OnHandShake])", sender.ConnectionId));
  342. return HandleResult.Ok;
  343. }
  344. /// <summary>
  345. /// 设置程序状态
  346. /// </summary>
  347. /// <param name="state"></param>
  348. void SetAppState(AppState state)
  349. {
  350. appState = state;
  351. this.btnStart.Enabled = (appState == AppState.Stoped);
  352. this.btnStop.Enabled = (appState == AppState.Started);
  353. this.txtIpAddress.Enabled = (appState == AppState.Stoped);
  354. this.txtPort.Enabled = (appState == AppState.Stoped);
  355. this.cbxAsyncConn.Enabled = (appState == AppState.Stoped);
  356. this.btnSend.Enabled = (appState == AppState.Started);
  357. this.btnSendFile.Enabled = (appState == AppState.Started);
  358. this.btnSendSerializableObject.Enabled = (appState == AppState.Started);
  359. }
  360. /// <summary>
  361. /// 往listbox加一条项目
  362. /// </summary>
  363. /// <param name="msg"></param>
  364. void AddMsg(string msg)
  365. {
  366. if (this.lbxMsg.InvokeRequired)
  367. {
  368. // 很帅的调自己
  369. this.lbxMsg.Invoke(AddMsgDelegate, msg);
  370. }
  371. else
  372. {
  373. if (this.lbxMsg.Items.Count > 100)
  374. {
  375. this.lbxMsg.Items.RemoveAt(0);
  376. }
  377. this.lbxMsg.Items.Add(msg);
  378. this.lbxMsg.TopIndex = this.lbxMsg.Items.Count - (int)(this.lbxMsg.Height / this.lbxMsg.ItemHeight);
  379. }
  380. }
  381. private void frmClient_FormClosed(object sender, FormClosedEventArgs e)
  382. {
  383. client.Destroy();
  384. }
  385. private void btnSendFile_Click(object sender, EventArgs e)
  386. {
  387. try
  388. {
  389. OpenFileDialog ofd = new OpenFileDialog();
  390. // ofd.InitialDirectory = "c:\\" ;
  391. //ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
  392. ofd.Filter = "txt files (*.txt)|*.txt";
  393. ofd.RestoreDirectory = true;
  394. ofd.CheckFileExists = true;
  395. ofd.CheckPathExists = true;
  396. if (ofd.ShowDialog() == DialogResult.OK)
  397. {
  398. SendFileToServer(ofd.FileName);
  399. }
  400. }
  401. catch (Exception ex)
  402. {
  403. MessageBox.Show(ex.Message);
  404. }
  405. }
  406. }
  407. [StructLayout(LayoutKind.Sequential, Pack = 1)]
  408. public struct MyFileInfo
  409. {
  410. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 255)]
  411. public string FilePath;
  412. public long FileSize;
  413. }
  414. /// <summary>
  415. /// 学员性别
  416. /// </summary>
  417. public enum Sex
  418. {
  419. /// <summary>
  420. /// 男
  421. /// </summary>
  422. Male = 1,
  423. /// <summary>
  424. /// 女
  425. /// </summary>
  426. Female = 2,
  427. /// <summary>
  428. /// 变性人
  429. /// </summary>
  430. Transsexual = 3,
  431. /// <summary>
  432. /// 未知
  433. /// </summary>
  434. Unknown = 4,
  435. }
  436. /// <summary>
  437. /// 学员类
  438. /// </summary>
  439. [Serializable]
  440. public class Student
  441. {
  442. /// <summary>
  443. /// 编号
  444. /// </summary>
  445. public int Id { get; set; }
  446. /// <summary>
  447. /// 姓名
  448. /// </summary>
  449. public string Name { get; set; }
  450. /// <summary>
  451. /// 性别
  452. /// </summary>
  453. public Sex Sex { get; set; }
  454. public string GetSexString()
  455. {
  456. string sex = string.Empty;
  457. switch (Sex)
  458. {
  459. case Sex.Male:
  460. sex = "男";
  461. break;
  462. case Sex.Female:
  463. sex = "女";
  464. break;
  465. case Sex.Transsexual:
  466. sex = "变性人";
  467. break;
  468. default:
  469. sex = "未知";
  470. break;
  471. }
  472. return sex;
  473. }
  474. }
  475. }