frame

NodeMCU: Unable to setup simple TCP server

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()

The code simply does following
1. Connect to Access Point.
2. Start a TCP server.

On execution I get only prints till ''print('Starting TCP server.')".

Thanks,
Mohsin 

Comments

  • anbaanba Member
    mohsinkhan
    thank you for using it :)

    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 try-except block.

    Anyway, you can use "," instead of "+" or convert tcp_srv_port to a string:
    print('Server Listening on ', tcp_srv_port, '...')

    print('Server Listening on ' + str(tcp_srv_port) + '...')

    With this small fix your code runs correctly.

    Andrea Baù
    Zerynth Support Team
  • 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 ?
      
  • anbaanba Member
    Indeed it is, here you can find some info.
    Feel free to ask for more details ;)
    Andrea Baù
    Zerynth Support Team
  • Thanks a lot.
Sign In or Register to comment.

ZERYNTH Community

@ 2016 Zerynth.com, all rights reserved.