对于我正在制作的iOS应用,它需要连接到python套接字服务器。对于iOS应用程序我正在使用Swift 3并且我正在使用BlueSocket当我尝试使用正确的IP和端口连接到服务器时,它总是返回Connection Refused并且我看不到连接服务器。 BlueSocket设置为TCP客户端,python服务器也是TCP服务器,所以我很困惑为什么它不工作。
有谁知道/理解为什么它不会连接到服务器?
iOS swift代码是这样的:
import UIKit
import Foundation
import SystemConfiguration
import SystemConfiguration.CaptiveNetwork
import Socket
let ssid = "SSID"
let server = "192.168.0.24"
let port = 8000
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var ideaLabel: UILabel!
@IBAction func generateButton(_ sender: Any) {
func isInternetAvailable() -> Bool
{
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
func getSSID() -> String? {
var ssid: String?
if let interfaces = CNCopySupportedInterfaces() as NSArray? {
for interface in interfaces {
if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
break
}
}
}
return ssid
}
func generateIdea() -> String? {
let RNumber = arc4random_uniform(23)
var idea = ""
//(A bunch of code to get a idea for offline mode)
return String(idea)
}
let InternetConnect = isInternetAvailable()
if (InternetConnect == isInternetAvailable()){
print("Internet Connection Verified")
if (getSSID() == ssid){
print("SSID Verified")
let s = try! Socket.create()
try! s.connect(to: server, port: 8000)
print("Connceted to server")
try! s.write(from: "01")
print("String send")
let idea = try! s.readString()
print("Idea Received")
ideaLabel.text = idea
s.close()
}
else{
print("SSID Verification Failed")
ideaLabel.text = generateIdea()
}
}
else {
ideaLabel.text = generateIdea()
print("Internet Connection Verification Failed")
}
}
}
swift客户端的说明:
当点击一个按钮产生一个想法时,应用程序首先检查它是否可以连接到互联网,如果它可以通过检查SSID检查它是否在设置的互联网上(服务器是将成为一个局域网服务器,因此它只适用于设置的网络)如果它无法连接到互联网或不在正确的网络上,它会选择存储在应用程序中的有限数量的想法。如果它可以连接到互联网及其在正确的互联网网络上,它会尝试连接到服务器并从服务器获取想法。
python套接字服务器代码:
import socket
import sqlite3
from random import randint
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 8000)
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")
print("Your idea is:")
print(idea)
connection.send(str(idea))
finally:
connection.close()
python套接字服务器的说明:
当服务器获得客户端时,它等待获取命令。在这个服务器中,只有一个命令,这是一个想法。那个命令是“01”。当它获得该命令时,它所做的第一件事就是获取存储在数据库中的想法量。这将写在maxID.txt文件中,因此它会读取它。然后随机选择一个随机的想法ID,然后通过使用ID从数据库中获取该想法。然后它接受了这个想法并将其发送给客户。
答案 0 :(得分:0)
问题出在python服务器上。问题是我将主机设置为localhost,而不是将其留空。
此:
server_address = ('localhost', 8000)
应该是:
server_address = ('', 8000)