简体   繁体   中英

Read from InputStream in Swift from Java Server

as the title says, I'm trying to read from an InputStream in Swift. I'm new to Swift so I'm having some troubles regarding how to read from the InputStream a message sent from the Java Server.

Java Server Code:

byte[] toSend = sec.initiateDH;

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

Swift Client Code

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")
   
}

Basically, I'm trying to initiate a DH key exchange. The Swift client sends their public key, and in return, the server is supposed to send back theirs. It does send, but I'm having trouble reading from the InputStream. First, the server sends the size and only then sends the byte array itself. Server uses DataOutputStream for writing.

Anyone can help me with this?

Thank you very much in advance!

Where is your code, what u mean about??

Well, u not send to mach information about what ur problem but I suppose that you want read an php file from sever so there is tow part: part one reading the php file in the swift part you need to add this code in 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?
           
             
           }
       }
   }

don't forget to import Alamofire at the beginning of ur code. and the php part "infoinputstream.php" or what ever ur php code supposed to be something like..

 <?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); ?>

Hope it's help..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM