title: Python read serial (RS-232) data over TCP/IP
body: <p>I am using a Moxa NPort 5110 serial-to-ethernet adapter to transfer serial data over a TCP/IP connection to my computer on port 4001.</p>
  
  <p>I am able to create a socket connection on <code>localhost:4001</code> to receive the data. The problem is that I can not use the data because it is not clean, it contains <strong>RS-232 bits</strong>.</p>
  
  <p>This is the code I used to create the socket connection and read the unclean data:</p>
  
  <pre><code>import socket 
  host = '' 
  port = 4001 
  backlog = 5 
  size = 1024 
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
  s.bind((host,port)) 
  s.listen(backlog) 
  while 1: 
      client, address = s.accept() 
      data = client.recv(size) 
      if data: 
          print(data)
      client.close()
  </code></pre>
  
  <p>Then I tried to use pyserial to make a socket connection and let pyserial interpret the data. Code:</p>
  
  <pre><code>import serial
  ser = serial.serial_for_url("socket://localhost:4001/logging=debug")
  data = ser.read(8)
  if data:
      print(data)
      ser.flushOutput()
  ser.close()
  </code></pre>
  
  <p>When I use this code I receive a <code>ConnectionRefusedError</code>. </p>
  
  <p>Any advice on how to establish a socket connection and use pyserial to read the data?</p>