Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //TelnetConnection stopConnection = new TelnetConnection();
- public partial class BarcodeReceivingForm : Form
- {
- //GLOBAL VARIABLES
- const string Hostname = "myip";
- private const int Port = 23;
- public BarcodeReceivingForm()
- {
- InitializeComponent();
- }
- private void btn_ConnectT_Click(object sender, EventArgs e)
- {
- var readData = new TelnetConnection(Hostname, Port);
- readData.ServerSocket(Hostname, Port);
- }
- private void btn_StopConnection_Click(object sender, EventArgs e)
- {
- //var connection = new TelnetConnection(Hostname, Port);
- // connection.CloseConnection();
- }
- }
- private Thread _readWriteThread;
- private TcpClient _client;
- private NetworkStream _networkStream;
- private string _hostname;
- private int _port;
- public TelnetConnection(string hostname, int port)
- {
- this._hostname = hostname;
- this._port = port;
- }
- public void ServerSocket(string ip, int port)
- {
- try
- {
- _client = new TcpClient(ip, port);
- }
- catch (SocketException)
- {
- MessageBox.Show(@"Failed to connect to server");
- return;
- }
- //Assign networkstream
- _networkStream = _client.GetStream();
- //start socket read/write thread
- _readWriteThread = new Thread(ReadWrite);
- _readWriteThread.Start();
- }
- public void ReadWrite()
- {
- //Set up connection loop
- while (true)
- {
- var command = "test";
- if (command == "STOP1")
- break;
- //write(command);
- var received = Read();
- BcForm.lst_BarcodeScan.Invoke(new Action (() => BcForm.lst_BarcodeScan.Items.Add(received)));
- }
- }
- public string Read()
- {
- byte[] data = new byte[1024];
- var received = "";
- var size = _networkStream.Read(data, 0, data.Length);
- received = Encoding.ASCII.GetString(data, 0, size);
- return received;
- }
- public void CloseConnection()
- {
- _networkStream.Close();
- _client.Close();
- }
- }
Add Comment
Please, Sign In to add comment