Skip to content

Instantly share code, notes, and snippets.

@mridah
Created August 1, 2018 06:23
Show Gist options
  • Save mridah/639d00464d7edd00dc307cc8b8833d86 to your computer and use it in GitHub Desktop.
Save mridah/639d00464d7edd00dc307cc8b8833d86 to your computer and use it in GitHub Desktop.
Sample program to read barcode data over TCP C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TCPListenerTest
{
public partial class Form1 : Form
{
private static TcpListener _TcpListener;
static Int32 port = 23;
IPAddress scannerIPAddress = IPAddress.Parse("192.168.0.100");
private static bool _QuitProcessing = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread thread = new Thread(ReceivePortMessages);
thread.IsBackground = true;
thread.Start();
}
private void ReceivePortMessages()
{
_TcpListener = new TcpListener(IPAddress.Any, port);
byte[] receiveBuffer = new byte[6400];
while (!_QuitProcessing)
{
int requestCount = 0;
_TcpListener.Start();
Console.WriteLine(" >> Listener Started");
using (var tcpClient = _TcpListener.AcceptTcpClient())
{
Console.WriteLine(" >> Accepted connection from client");
using (var networkStream = tcpClient.GetStream())
{
while (!_QuitProcessing)
{
try
{
requestCount = requestCount++;
var bytesRead = networkStream.Read(receiveBuffer, 0, (int)tcpClient.ReceiveBufferSize);
if (bytesRead == 0)
{
// Read returns 0 if the client closes the connection
break;
}
string dataFromClient = System.Text.Encoding.ASCII.GetString(receiveBuffer, 0, bytesRead);
Console.WriteLine(dataFromClient);
}
catch (Exception ex)
{
Console.WriteLine("ReceivePortMessages: " + ex.ToString());
break;
}
}
}
Console.WriteLine(" >> stopped read loop");
}
_TcpListener.Stop();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment