# Wednesday, May 07, 2008

Powershell TCP Listener

The project I'm currently working on is an embedded device without any graphical interface capability. The only ways to get some information out is the NIC or a serial port. There is also a CAN-Bus interface, but as far as my company developed the device it is better to not base our debugging capabilities on a potentially buggy part of the system. Out first debug out was implemented as a serial output tracer. As the day comes closer that out hardware prototypes will arrive, the higher the need to port the tracing over to the NIC as far as the final hardware won't have a serial port on it.
So last week the network tracer was check in into source control. Now, how to read these information?
Windows ships with Hyper Terminal. But this isn't very comfortable and you manually have to reestablish a lost connection. In my today's lunch break I wrote a small powershell script that listens to the network socket. At the moment I'm porting it to C# to add some more features.

But here is the first part, a small and simple powershell script to listen to a network socket. But please let me clarify that this is code snippet is NOT the way code. It was a fast hack to get it running. There is no error handling and ressources are not freed gracefully as it has to be terminated with ctrl + c. In clear words: This is a sample on how to receive data from a network socket.

$socket = new-object System.Net.Sockets.TcpClient("172.16.170.123", 9950)
if($socket -eq $null) { return; }
$stream = $socket.GetStream()
$buffer = new-object System.Byte[] $socket.ReceiveBufferSize
$encoding = new-object System.Text.AsciiEncoding

while($true)
{
   if($stream.DataAvailable)
   {
      $read = $stream.Read($buffer, 0, $socket.ReceiveBufferSize)  
      write-host -n ($encoding.GetString($buffer, 0, $read))
   }
}

Wednesday, May 07, 2008 9:47:07 PM (W. Europe Daylight Time, UTC+02:00) #    Comments [0] | Trackback
Comments are closed.