从 Java Server 的 Swift 中的 InputStream 读取

问题描述

正如标题所说,我正在尝试从 Swift 中的 InputStream 读取。我是 Swift 的新手,所以我在如何从 InputStream 读取从 Java 服务器发送的消息方面遇到了一些麻烦。

Java 服务器代码

byte[] toSend = sec.initiateDH;

out.writeInt(toSend.length);
out.write(toSend);

Swift 客户端代码

init(_ ipAddress: String,_ port: Int,_ textEncoding: String.Encoding) {
    super.init()
    Stream.getStreamsToHost(withName: ipAddress,port: port,inputStream: &inp,outputStream: &out)
    
    
    inp!.open()
    out!.open()

    
    print("Connection Established")
   
}

基本上,我正在尝试发起 DH 密钥交换。 Swift 客户端发送他们的公钥,作为回报,服务器应该发回他们的公钥。它确实发送,但我在从 InputStream 读取时遇到问题。首先,服务器发送大小,然后才发送字节数组本身。服务器使用 DataOutputStream 进行写入。

有人可以帮我解决这个问题吗?

在此先非常感谢您!

解决方法

你的代码在哪里,你的意思是什么??

,

好吧,你不会向 mach 发送关于你的问题的信息,但我想你想从服务器读取一个 php 文件,所以有两个部分: 第一部分在 swift 部分读取 php 文件,您需要在 viewDidload() func 中添加此代码:

let URL_USER_data = "https://www.ursite.net/infoinputstream.php"

    override func viewDidLoad() {
       super.viewDidLoad()
       //Sending http post request
       Alamofire.request(URL_USER_data,method: .get).responseJSON
       {
           response in
           //printing response
           print(response)
           //getting the json value from the server
           if let result = response.result.value {
               //converting it as NSDictionary
               let jsonData = result as! NSDictionary
               //displaying the message in label
               self.bytetext.text = jsonData.value(forKey: "byte") as! String?
               self.sizetext.text = jsonData.value(forKey: "size") as! String?
           
             
           }
       }
   }

不要忘记在代码的开头导入 Alamofire。 和 php 部分“infoinputstream.php”或你的 php 代码应该是什么东西..

<?php 

require_once 'connect.php';


        $query1="SELECT* FROM data";
        $result1 = mysqli_query($conn,$query1);
          while( $row1 = mysqli_fetch_assoc($result1) ){
          
            $$response=$row1['byte'];
             $$response=$row1['size'];
      
             
          }
          echo json_encode($response);   
          ?>

希望对你有帮助..