NodeMCU: Unable to setup simple TCP server


#1

Hi, 

First of all many thanks for developing this platform.
I’m trying to setup simple  TCP server with no luck. Simple Web server example is working fine but I can’t really figure out what is wrong in my code

# stream for serial activity
import streams

socket module to TCP

import socket

generic wifi APIs

from wireless import wifi

esp8266 wifi driver

from espressif.esp8266wifi import esp8266wifi as wifi_driver

constants

ap_name = ‘AHS’
ap_pass = ‘12345687’

tcp_srv_port = 80
tcp_srv_max_clnt = 2

init serial

streams.serial()

connect to access point

print('Connect to Access Point: ’ + ap_name)

init esp8266 wifi driver

print(‘Init ESP8266 WiFi driver…’)
wifi_driver.auto_init()

try to connect to Access Point

tries = 0
while not wifi.is_linked() and tries < 5:
try:
wifi.link(ap_name, wifi.WIFI_WPA2, ap_pass)
except Exception as e:
pass
tries += 1

ip = wifi.link_info()[0]

print('IP Address: ’ + ip)

print(‘Starting TCP server.’)

create a tcp socket

sock = socket.socket()

bind the socket to port

sock.bind(tcp_srv_port)

set the socket in listening mode

sock.listen()
print('Server Listening on ’ + tcp_srv_port + ‘…’)
while True:
# accept incoming connections from clients
client,addr = sock.accept()
# send something to the client and close
client.sendall(“Hello!”)
client.close()

<br>The code simply does following<br>1. Connect to Access Point.<br>2. Start a TCP server.<br><br>On execution I get only prints till ''<span>print('Starting TCP server.')".<br><br>Thanks,<br>Mohsin&nbsp;</span>

#2

Hi @mohsinkhan
thank you for using it :slight_smile:

The error in the script is at this line:

print('Server Listening on ’ + tcp_srv_port + ‘…’)
Trying to concatenate strings and int raise a TypeError exception. You can check it out yourself putting the code in a <a rel="nofollow" target="_blank" href="https://docs.zerynth.com/latest/official/core.zerynth.stdlib/examples/examples.html#exceptions-debugger">try-except</a> block.<br><br>Anyway, you can use "," instead of "+" or convert tcp_srv_port to a string:<br><pre class="CodeBlock">print('Server Listening on ', tcp_srv_port, '...')<br><br>print('Server Listening on ' + str(tcp_srv_port) + '...')

With this small fix your code runs correctly.


#3

Thank you very much. 
I didn’t thought of making such a trivial mistake. 

You develop such habits not taking care of these small mistakes while you program Python on PCs.

In the context of the problem I would like to ask another question

In standard Python you get an exception trace in such scenarios if you haven’t implemented try-catch, Is this different in Zeryntn ?
  


#4

Indeed it is, here you can find some info.
Feel free to ask for more details :wink:


#5

Thanks a lot.