我有想法将我的wifi墙式适配器连接到我的电脑。我第一次看到其他想法,发现链接:Connecting through pc 在这个链接中是一个python代码,我也尝试过并完美地为我工作。比我试图在Swift中重建它并找到Socketswift。我实现了它并试图用端口8530连接到“192.168.2.131”,它没有用。我收到了失败:“连接超时”。到目前为止,我无法弄清楚我做错了什么,因为当我通过python尝试同样的事情时它起作用。 这是我的python代码:
d = socket.socket()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,0)
s.connect(('192.168.2.131', 8530)) # (IP, Port) is a single variable passed to connect function
s.send(bytearray.fromhex('01 40' + mac + on)) # to switch 'on'
time.sleep(5) # sleep for 5 seconds
这是我的IOS / Swift代码:
let client = TCPClient(address: "192.168.2.131", port: 8530)
switch client.connect(timeout: 10){
case .success:
print("connected")
var hex: String = String("01 40" + mac + off)
var byteArray = [UInt8]()
byteArray += hex.utf8
let data: Data = Data(bytes: byteArray)
let result = client.send(data: data)
case .failure(let error):
print(error)
}
感谢您的回答。如果您有任何疑问或需要更多信息,请给我发消息
答案 0 :(得分:0)
如果我在python中使用TCP套接字,我会在connect()
调用时收到超时错误 - 就像你的iOS代码一样。
这是一个你可以玩的python TCP客户端:
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #SOCK_STREAM => TCP, SOCK_DGRAM => UDP
s.settimeout(10)
s.connect(('192.168.2.131', 8530))
s.send(bytearray.fromhex('01 40')) # to switch 'on'
time.sleep(20)
结果:
~/python_programs$ p34 1.py
Traceback (most recent call last):
File "1.py", line 6, in <module>
s.connect(('192.168.2.131', 8530))
socket.timeout: timed out
尝试在设置中使用python TCP代码。我猜它不起作用,因为iOS TCP代码不起作用。接下来,因为您说python UDP代码适合您,我会尝试creating a UDP socket with SwiftSocket。
答案 1 :(得分:0)
这是使用安装了cocoapods的SwiftSocket的示例UDP客户端和服务器:
import UIKit
import SwiftSocket
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//This can be a server using localhost on your Macbook as well.
DispatchQueue.global(qos: .background).async {
let udpServer = UDPServer(address: "127.0.0.1", port:12033)
var count = 1
while true {
print("Server about to recv() \(count)")
let(byteArray, sender, port) = udpServer.recv(1024)
if let byteArray = byteArray,
let string = String(data: Data(byteArray), encoding: .utf8)
{
print("Server received: \(string)\nsender: \(sender)\nport: \(port)\n\n")
}
count += 1
}
}
DispatchQueue.global(qos: .background).async {
let udpClient = UDPClient(address: "127.0.0.1", port: 12033)
switch udpClient.send(string: "Hello") {
case .success:
print("Client sent message to server.")
case .failure(let error):
print("Client failed to send message to server: \(error)")
}
udpClient.close()
DispatchQueue.main.async {
//This is run on the main queue, after the previous
//code executes. Update UI here.
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
--output:--
Server about to recv() 1
Client sent message to server.
Server received: Hello
sender: 127.0.0.1
port: 42998
Server about to recv() 2