Form1.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using SocketToolbox;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using System.Windows.Forms;
  14. namespace socketTest
  15. {
  16. public partial class Form1 : Form
  17. {
  18. public Form1()
  19. {
  20. InitializeComponent();
  21. Task.Factory.StartNew(()=> {
  22. while (true)
  23. {
  24. if (SocketLinker.ins != null && SocketLinker.CurrentHandler!=null)
  25. {
  26. richTextBox2.Text = Encoding.ASCII.GetString(SocketLinker.CurrentHandler.receiveBuffer);
  27. }
  28. Thread.Sleep(2000);
  29. }
  30. });
  31. }
  32. private void button1_Click(object sender, EventArgs e)
  33. {
  34. if(SocketLinker.ins == null)
  35. {
  36. SocketLinker.ins = new SocketLinker();
  37. MessageBox.Show("已连接");
  38. }
  39. else
  40. {
  41. MessageBox.Show("请勿重复连接");
  42. }
  43. }
  44. private void button2_Click(object sender, EventArgs e)
  45. {
  46. IPEndPoint remoteIPE = new IPEndPoint(IPAddress.Parse("192.168.1.102"), 7);
  47. SocketHandler sh = new SocketHandler(999, remoteIPE);
  48. sh.StartSend();
  49. string str = richTextBox1.Text;
  50. char[] chars = str.ToCharArray();
  51. byte[] bytes = new byte[chars.Length];
  52. for(int i = 0; i < chars.Length; i++)
  53. {
  54. bytes[i] = Convert.ToByte(chars[i]);
  55. }
  56. while (!sh.writeAvailable) { }
  57. sh.Send(bytes);
  58. MessageBox.Show("已发送:"+Encoding.ASCII.GetString(bytes));
  59. }
  60. }
  61. }