尝试连接到python TCP套接字服务器时,Swift3 SwiftSocket返回UnknownError

时间:2017-05-31 16:32:12

标签: python sockets tcp swift3

我为手机制作了Swift iOS应用程序。它需要连接到python套接字服务器。当我使用终端在我的mac上telnet时,服务器工作正常,但是当我尝试使用应用程序连接时,应用程序返回UnknownError。但是当我输入时,例如www.google.com和端口80,或者当我在本地网络上使用网页设备时,它可以正常工作。为什么它没有连接,我该如何解决?

以下是我使用的库的链接:https://github.com/swiftsocket/SwiftSocket

以下是设备上使用的代码:

let host = "192.168.0.24"
let port = 250
var client: TCPClient?
client = TCPClient(address: host, port: Int32(port))

guard let client = client else { return }

            switch client.connect(timeout: 10) {
            case .success:
                appendToTextField(string: "Connected to host \(client.address)")
                if let response = sendRequest(string: "01", using: client) {
                    appendToTextField(string: "Response: \(response)")
                    ideaLabel.text = readResponse(from: client)
                }
            case .failure(let error):
                appendToTextField(string: String(describing: error))
            }

这是服务器代码:

import socket
import sqlite3
from random import randint

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 250)
print("Starting Server")
s.bind(server_address)
print("Waiting for client")
s.listen(1)
alive = True

while(alive == True):
    connection, client_address = s.accept()
    print(client_address)

    try:
        command = connection.recv(2)

        if (command == "01"):
           conn = sqlite3.connect('ideas.db')
           c = conn.cursor()
           file = open("maxID.txt", "r")
           maxID = (int(file.read()) + 1)
           ideaNumber = (randint(1,maxID),)
           c.execute('SELECT * FROM ideas WHERE id=?', ideaNumber)
           idea1 = c.fetchone()
           idea = str(idea1)
           conn.close()
           idea = idea.translate(None, "1234567890'(),u")
           #idea = idea.translate("u",".")
           print("Your idea is:")
           print(idea)
           connection.send(str(idea))

   finally:
       connection.close()

0 个答案:

没有答案