0

I have recently starting learning network programming with python. Here is a simple server I tried to write:

import socket

def server():
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(('127.0.0.1', 1024))
    while True:
        data, address = sock.recvfrom(65535)
        text = data.decode('ascii')
        print('the client from {0} sent: "{1}"'.format(address, text))
        if text is '0': break

I wanted the server to wait till it is getting packets from the server, but when I run it, it will close instantly. what did I do wrong?

Auguste
  • 2,007
  • 2
  • 17
  • 25
Bar K
  • 89
  • 1
  • 7
  • 2
    Is that *all* of the code? – Ignacio Vazquez-Abrams Jun 02 '16 at 19:38
  • 1
    aside from not calling `server()` the conditional `if text is '0'` will never come true, see http://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce – Tadhg McDonald-Jensen Jun 02 '16 at 19:41
  • 2
    Check out the youtube video titled [David Beazley - Python Concurrency From the Ground Up](https://www.youtube.com/watch?v=MCs5OvhV9S4) for a crash course on writing a server in Python. – martineau Jun 02 '16 at 19:50

1 Answers1

3

You're not actually calling server().

Add this after the function definition:

if __name__ == '__main__':
  server()
Steven Mercatante
  • 24,757
  • 9
  • 65
  • 109
  • 3
    @BarK You may check this `Answer` as answering your question so we all stop spending time reviewing it over and over ? ;-) No need to be ashamed BTW you're learning, we're all still learning, even 20 years later. – Julien Palard Jun 02 '16 at 19:56