views:

471

answers:

3

Hi, Can someone please tell how to write a Non-Blocking server code using the socket library alone.Thanks

A: 

Not sure what you mean by "socket library alone" - you surely will need other modules from the standard Python library.

The lowest level of non-blocking code is the select module. This allows you to have many simultaneous client connections, and reports which of them have input pending to process. So you select both the server (accept) socket, plus any client connections that you have already accepted. A thin layer on top of that is the asyncore module.

Martin v. Löwis
+2  A: 

Why socket alone? It's so much simpler to use another standard library module, asyncore -- and if you can't, at the very least select!

If you're constrained by your homework's condition to only use socket, then I hope you can at least add threading (or multiprocessing), otherwise you're seriously out of luck -- you can make sockets with timeout, but juggling timing-out sockets without the needed help from any of the other obvious standard library modules (to support either async or threaded serving) is a serious mess indeed-y...;-).

Alex Martelli
+4  A: 

Frankly, just don't (unless it's for an exercise). The Twisted Framework will do everything network-related for you, so you have to write only your protocol without caring about the transport layer. Writing socket code is not easy, so why not use code somebody else wrote and tested.

Lukáš Lalinský
Indeed use twisted, I once wrote an event based socket library myself, it's a pain in the a... Even simple things like checking wether a connection was closed by the client or by an error can get you in a lot of trouble. It's definively only worth it if you want to learn a lot about how sockets work, but it's a lot of trial and error.
Ivo Wetzel