0

我想在 kotlin/native 中编写带有套接字连接的简单程序:

有打开和绑定套接字的简单功能。

actual fun openSocket(endpoint: IpPort): Socket {
    // Initialize sockets in platform-dependent way.
    init_sockets()
    var socketDescriptor = 0
    memScoped {
        val serverAddr = alloc<sockaddr_in>()
        socketDescriptor = socket(AF_INET, SOCK_STREAM, 0)
            .ensureUnixCallResult("socket") { !it.isMinusOne() }
        with(serverAddr) {
            memset(this.ptr, 0, sockaddr_in.size.narrow())
            sin_family = AF_INET.convert()
            sin_addr.s_addr = inet_addr(endpoint.cstr.ptr); /
            //sin_port = htons(endpoint.port.convert()) 
        }
        bind(socketDescriptor, serverAddr.ptr.reinterpret(), sockaddr_in.size.convert())
            .ensureUnixCallResult("bind") { it == 0 }
    }
    return Socket(socketDescriptor)
}

编译器 (./gradlew compileKonan) 无法解析函数:inet_addr, htons. 还有编译器解析器导入import platform.ios.*。我认为这些功能应该在 iOS 系统(和任何其他操作系统)头文件上。

有的build.gradle_

apply plugin: 'konan'

konan.targets = ['iphone']

konanArtifacts {
    framework('MezzoCore') {
        enableMultiplatform true   
    }
}

dependencies {
    expectedBy project(':common')
}

我不明白我做错了什么。谁能帮我?

4

1 回答 1

0

以下可能会有所帮助:

import platform.posix.*
import platform.darwin.*
import kotlinx.cinterop.*

// Just to avoid import conflict.
typealias sockaddr_in = platform.posix.sockaddr_in

fun main() {
   val endpoint ="127.0.0.1"
   val port = 8080
   var socketDescriptor = 0
   memScoped {
       val serverAddr = alloc<sockaddr_in>()
       socketDescriptor = socket(AF_INET, SOCK_STREAM, 0)
       with(serverAddr) {
           memset(this.ptr, 0, sockaddr_in.size.convert())
           sin_family = AF_INET.convert()
           sin_addr.s_addr = inet_addr(endpoint)
           sin_port = ((port shr 8) or ((port and 0xff) shl 8)).toUShort()
        }
        bind(socketDescriptor, serverAddr.ptr.reinterpret(), 
                 sockaddr_in.size.convert())
     }
     println("sd=$socketDescriptor")   
}
于 2018-09-14T17:37:03.430 回答