让iOS应用与我的家用服务器通信

1 投票
1 回答
1239 浏览
提问于 2025-04-17 19:29

目前,我在衣柜里有一台家用服务器,基本上没什么用处。它安装了Ubuntu Server 8.0.4,还有apache,用于我稍后要进行的网页开发,另外还安装了ssh和python/twisted。

现在的问题是:

我创建了一个应用程序,可以通过socket与“localhost”的40号端口进行通信,这里有一个我参考的链接,想要在此基础上进行开发:http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server

现在连接到localhost没有问题,但我想把这个功能扩展到我的服务器上。

我在服务器上实现了python协议,并且在iOS应用中更改了我访问的IP地址。我的实现和教程完全一样,只是我访问的端口不同。

from twisted.internet.protocol import Factory, Protocol

from twisted.internet import reactor

class IphoneChat(Protocol):

    def connectionMade(self):
        self.factory.clients.append(self)
        print "clients are ", self.factory.clients

    def connectionLost(self, reason):
        self.factory.clients.remove(self)

    def dataReceived(self, data):
        a = data.split(':')
        print a
        #b = password.split(':')
        #print b
        if len(a) > 1:
            command = a[0]
            content = a[1]
            #username = a[2]
            #password = a[2]

            msg = ""
            #msg2 = ""
            if command == "username":
                self.name = data
                msg = self.name + " has joined"
                #self.name = password
                #msg2 = self.name + " this is his password"
                #print msg

            elif command == "password":
                self.name = data
                msg = self.name + " this is their password"

            elif command == "msg":
                msg = self.name + ": " + data
                print msg
                #msg2 = self.name + ": " + password
                #print msg2

            for c in self.factory.clients:
                c.message(msg)#1, msg2)

    def message(self, message):
        self.transport.write(message + '\n')


factory = Factory()

factory.protocol = IphoneChat #here1#

factory.clients = []

reactor.listenTCP(40, factory)

print "Iphone Chat server started"

reactor.run()

所以真正的问题是,我无法将客户端连接到我的服务器,或者说是其他什么问题……抱歉,我对网络方面的知识还很有限。

任何意见都会很有帮助。

1 个回答

1

如果你之前没有从互联网与服务器建立网络通信,建议你先用一些简单的测试案例来确认这一点。因为有很多因素可能会阻止互联网流量到达你服务器上的程序。

你的服务器是通过路由器连接到互联网的吗?如果是的话,你能否在本地网络内与服务器进行通信(也就是说,使用类似于 192.168.xxx.xxx 的 IP 地址),可以尝试用 netcattelnet 来测试一下?

如果这样可以成功,那就试试从网络外部访问(也就是使用其他的 IP 地址,可以在 whatismyip.net 或类似网站上找到)。如果你对网络没有任何经验,可能会忘记设置端口转发,这个设置是在你的路由器上。

网上有很多教程教你如何设置一个 Ubuntu 家庭服务器,我建议你学习如何托管一个(非常)简单的网页,这样可以帮助你了解网络的基本知识,这对调试你正在制作的网络程序会有很大帮助。

撰写回答