0

using jython as a CGI-Server via 'jython -m CGIHTTPServer' results in an error which is not present with C-Python: error: (20000, 'socket must be in non-blocking mode').

If one (like me) wants to use jython as a simple CGI-Server for jython models, scripts etc. this is unacceptable. I found a solution to this and hope this helps others too:

Edit the file jython/Lib/select.py and go to the marked lines and add the two lines with the arrows (see below). Then all works well as known from C-Python.

jython/Lib/select.py:

... 

class poll:

... 

  def register(self, socket_object, mask = POLLIN|POLLOUT|POLLPRI):
      try:            

          try:    socket_object.setblocking(0)  # <-- line to add
          except: pass                          # <-- line to add

          channel = _getselectable(socket_object)
          if channel is None:
              # The socket is not yet connected, and thus has no channel
              # Add it to a pending list, and return
              self.unconnected_sockets.append( (socket_object, mask) )
              return
          self._register_channel(socket_object, channel, mask)
      except java.lang.Exception, jlx:
          raise _map_exception(jlx)

  ...
Michael Hecht
  • 2,093
  • 6
  • 25
  • 37

1 Answers1

0

With some applications I got trouble with setblocking(0) during response. So I also modified jython/Lib/socket.py as follows:

jython/Lib/socket.py:

class _tcpsocket(_nonblocking_api_mixin): 

  ...

  def send(self, s):
      try:
          if not self.sock_impl: raise error(errno.ENOTCONN, 'Socket is not connected')
          if self.sock_impl.jchannel.isConnectionPending():
            self.sock_impl.jchannel.finishConnect()
          numwritten = self.sock_impl.write(s)            

          # try again in blocking mode
          if numwritten == 0 and self.mode == MODE_NONBLOCKING: # <-- line to add
            try:    self.setblocking(1)                         # <-- line to add
            except: pass                                        # <-- line to add
            numwritten = self.sock_impl.write(s)                # <-- line to add


          if numwritten == 0 and self.mode == MODE_NONBLOCKING:
              raise would_block_error()
          return numwritten
      except java.lang.Exception, jlx:
          raise _map_exception(jlx)

  ...   

I know that both changes are not very 'clean' but the only way to get Jython as CGIHTTPServer working like Python.

Michael Hecht
  • 2,093
  • 6
  • 25
  • 37