我在Android设备上创建了一个热点/ wifi-direct。并将此wifi连接到iOS设备。 现在我想创建一个iOS应用程序,它将能够通过wifi发送和接收数据。 如果是,那么我可以做到这一点吗?
答案 0 :(得分:0)
是的,有可能,你可以在android上运行本地服务器,我推荐https://github.com/NanoHttpd/nanohttpd 那么你必须在iOS设备上获取ip地址来做http请求,有c方法来获取路由ip地址
#include "IpHelper.h" // my header file
#include <stdio.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <string.h>
#include <arpa/inet.h>
#if TARGET_IPHONE_SIMULATOR
#include <net/route.h>
#else
#include "route.h"
#endif
#define CTL_NET 4 /* network, see socket.h */
#if defined(BSD) || defined(__APPLE__)
#define ROUNDUP(a) \
((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
int getdefaultgateway(in_addr_t * addr)
{
int mib[] = {CTL_NET, PF_ROUTE, 0, AF_INET,
NET_RT_FLAGS, RTF_GATEWAY};
size_t l;
char * buf, * p;
struct rt_msghdr * rt;
struct sockaddr * sa;
struct sockaddr * sa_tab[RTAX_MAX];
int i;
int r = -1;
if(sysctl(mib, sizeof(mib)/sizeof(int), 0, &l, 0, 0) < 0) {
return -1;
}
if(l>0) {
buf = malloc(l);
if(sysctl(mib, sizeof(mib)/sizeof(int), buf, &l, 0, 0) < 0) {
return -1;
}
for(p=buf; p<buf+l; p+=rt->rtm_msglen) {
rt = (struct rt_msghdr *)p;
sa = (struct sockaddr *)(rt + 1);
for(i=0; i<RTAX_MAX; i++) {
if(rt->rtm_addrs & (1 << i)) {
sa_tab[i] = sa;
sa = (struct sockaddr *)((char *)sa + ROUNDUP(sa->sa_len));
} else {
sa_tab[i] = NULL;
}
}
if( ((rt->rtm_addrs & (RTA_DST|RTA_GATEWAY)) == (RTA_DST|RTA_GATEWAY))
&& sa_tab[RTAX_DST]->sa_family == AF_INET
&& sa_tab[RTAX_GATEWAY]->sa_family == AF_INET) {
if(((struct sockaddr_in *)sa_tab[RTAX_DST])->sin_addr.s_addr == 0) {
char ifName[128];
if_indextoname(rt->rtm_index,ifName);
if(strcmp("en0",ifName)==0){
*addr = ((struct sockaddr_in *)(sa_tab[RTAX_GATEWAY]))->sin_addr.s_addr;
r = 0;
}
}
}
}
free(buf);
}
return r;
}
#endif
你还需要从这里的https://opensource.apple.com/source/xnu/xnu-1456.1.26/bsd/net/route.h
下载并从apple open-sources导入route.h最后,您可以获得本地http网址http://+'ip you get before'+ :'port of server you lunched on android'
所以,现在您已准备好通过ALamofire(或其他)向本地服务器发送http请求。
编辑1: 我在旧项目中找到了这个代码,你可以用CocoaAsyncSocket进行数据传输,它是用swift 3编写的,我知道你想要一些写在objC上的代码,但是找不到这个,对不起,如果我不能完全回答你的问题
import CocoaAsyncSocket
import UIKit
enum TAG: Int {
case header = 1
case body = 2
}
class ViewController: UIViewController, NetServiceDelegate, NetServiceBrowserDelegate, GCDAsyncSocketDelegate {
var service : NetService!
var socket : GCDAsyncSocket!
var newSocket: GCDAsyncSocket!
var serviceBrowser = NetServiceBrowser()
var adresses: [Data]?
override func viewDidLoad() {
super.viewDidLoad()
startTalking()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func parseHeader(data: NSData) -> UInt {
var out: UInt = 0
data.getBytes(&out, length: MemoryLayout<UInt>.size)
return out
}
func handleResponseBody(data: NSData) {
if let message = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) {
print(message)
}
}
func sendText() {
if let data = "aaaaa".data(using: String.Encoding.utf8) {
var header = data.count
let headerData = NSData(bytes: &header, length: MemoryLayout<UInt>.size)
self.socket.write(headerData as Data, withTimeout: -1.0, tag: TAG.header.rawValue)
self.socket.write(data, withTimeout: -1.0, tag: TAG.body.rawValue)
}
}
func startTalking () {
self.socket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
self.socket.isIPv4PreferredOverIPv6 = false
do {
try self.socket.connect(toHost: "localhost", onPort: UInt16(8080), withTimeout: -1)
} catch let err {
print(err)
}
}
/*
* Delegates of NSNetService
**/
func netServiceBrowser(_ browser: NetServiceBrowser, didFindDomain domainString: String, moreComing: Bool) {
print(111)
}
func netService(_ sender: NetService, didNotResolve errorDict: [String : NSNumber]) {
print("aaaaaaa")
}
func netServiceDidPublish(_ sender: NetService) {
print("Bonjour service published. domain: \(sender.domain), type: \(sender.type), name: \(sender.name), port: \(sender.port)")
}
func netService(_ sender: NetService, didNotPublish errorDict: [String : NSNumber]) {
print("Unable to create socket. domain: \(sender.domain), type: \(sender.type), name: \(sender.name), port: \(sender.port), Error \(errorDict)")
}
func netService(_ sender: NetService, didAcceptConnectionWith inputStream: InputStream, outputStream: OutputStream) {
print("4")
}
/*
* END OF Delegates
**/
/*
* Delegates of GCDAsyncSokcket
**/
func socketDidSecure(_ sock: GCDAsyncSocket) {
print("3")
}
func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
print("connected")
self.socket.readData(toLength: UInt(MemoryLayout<UInt64>.size), withTimeout: -1, tag: 0)
}
func socket(_ sock: GCDAsyncSocket, didAcceptNewSocket newSocket: GCDAsyncSocket) {
print("Did accept new socket")
self.newSocket = newSocket
self.newSocket.readData(toLength: UInt(MemoryLayout<UInt64>.size), withTimeout: -1.0, tag: 0)
print("Connected to " + self.service.name)
}
func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
print("Socket disconnected: error \(err)")
if self.socket == socket {
// print("Disconnected from " + self.service.name)
}
}
func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
if data.count == MemoryLayout<UInt>.size {
let bodyLength: UInt = self.parseHeader(data: data as NSData)
sock.readData(toLength: bodyLength, withTimeout: -1, tag: TAG.body.rawValue)
} else {
self.handleResponseBody(data: data as NSData)
sock.readData(toLength: UInt(MemoryLayout<UInt>.size), withTimeout: -1, tag: TAG.header.rawValue)
}
}
func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
print("Write data with tag of \(tag)")
}
func socket(_ sock: GCDAsyncSocket, didReceive trust: SecTrust, completionHandler: @escaping (Bool) -> Void) {
completionHandler(true)
}
/*
* END OF Delegates
**/
}
编辑2: 要将ip解析为人类可读的字符串,这是Objc方法
+ (NSString *)getGatewayIP {
NSString *ipString = nil;
struct in_addr gatewayaddr;
int r = getdefaultgateway(&(gatewayaddr.s_addr));
if(r >= 0) {
ipString = [NSString stringWithFormat: @"%s",inet_ntoa(gatewayaddr)];
NSLog(@"default gateway : %@", ipString );
} else {
NSLog(@"getdefaultgateway() failed");
}
return ipString;
}