3

I build a socket server with python's SocketServer module:

import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        print self.data
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    server.serve_forever()

I can access server with http://localhost:9999/ in my computer, but I cannot access with my phone(my phone is in local area network because I connect the wifi from computer.) with IP:http://192.168.123.1:9999.

I have used python -m SimpleHTTPServer 9999 to test my network, I can access my computer with my phone.

roger
  • 9,063
  • 20
  • 72
  • 119

2 Answers2

3

Because the code is specifying localhost host as a host. To allow any hosts to access the port, you need to specify it as '0.0.0.0' or ''.

HOST, PORT = "", 9999

server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

server.serve_forever()
falsetru
  • 357,413
  • 63
  • 732
  • 636
1

When you say localhost as the server's host name, the HTTP server will pick only the requests targetted at localhost or 127.0.0.1. When you access it from your mobile, you would probably be accessing it with the actual IP address of the computer, which will not be 127.0.0.1 or localhost. That is why the server is not picking up those requests.

To specify that you want to respond to all the requests targetted at this machine, irrespective of the IP address or host name used to access the server, you would use 0.0.0.0 as the HOST

HOST, PORT = "0.0.0.0", 9999
thefourtheye
  • 233,700
  • 52
  • 457
  • 497