Guest User

Untitled

a guest
Jan 20th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. //TelnetConnection stopConnection = new TelnetConnection();
  2. public partial class BarcodeReceivingForm : Form
  3. {
  4. //GLOBAL VARIABLES
  5. const string Hostname = "myip";
  6. private const int Port = 23;
  7.  
  8.  
  9. public BarcodeReceivingForm()
  10. {
  11. InitializeComponent();
  12. }
  13.  
  14. private void btn_ConnectT_Click(object sender, EventArgs e)
  15. {
  16.  
  17. var readData = new TelnetConnection(Hostname, Port);
  18. readData.ServerSocket(Hostname, Port);
  19.  
  20. }
  21.  
  22. private void btn_StopConnection_Click(object sender, EventArgs e)
  23. {
  24. //var connection = new TelnetConnection(Hostname, Port);
  25. // connection.CloseConnection();
  26. }
  27. }
  28.  
  29. private Thread _readWriteThread;
  30. private TcpClient _client;
  31. private NetworkStream _networkStream;
  32. private string _hostname;
  33. private int _port;
  34.  
  35. public TelnetConnection(string hostname, int port)
  36. {
  37. this._hostname = hostname;
  38. this._port = port;
  39. }
  40.  
  41. public void ServerSocket(string ip, int port)
  42. {
  43.  
  44. try
  45. {
  46. _client = new TcpClient(ip, port);
  47. }
  48. catch (SocketException)
  49. {
  50. MessageBox.Show(@"Failed to connect to server");
  51. return;
  52. }
  53.  
  54. //Assign networkstream
  55. _networkStream = _client.GetStream();
  56.  
  57. //start socket read/write thread
  58. _readWriteThread = new Thread(ReadWrite);
  59. _readWriteThread.Start();
  60. }
  61.  
  62. public void ReadWrite()
  63. {
  64.  
  65. //Set up connection loop
  66. while (true)
  67. {
  68. var command = "test";
  69. if (command == "STOP1")
  70. break;
  71.  
  72. //write(command);
  73. var received = Read();
  74.  
  75.  
  76. BcForm.lst_BarcodeScan.Invoke(new Action (() => BcForm.lst_BarcodeScan.Items.Add(received)));
  77.  
  78.  
  79. }
  80.  
  81. }
  82.  
  83. public string Read()
  84. {
  85. byte[] data = new byte[1024];
  86. var received = "";
  87.  
  88. var size = _networkStream.Read(data, 0, data.Length);
  89. received = Encoding.ASCII.GetString(data, 0, size);
  90.  
  91. return received;
  92. }
  93.  
  94. public void CloseConnection()
  95. {
  96. _networkStream.Close();
  97. _client.Close();
  98. }
  99. }
Add Comment
Please, Sign In to add comment