I'm testing to connect and send a simple message to a host and I've used this guide http://studyswift.blogspot.com/2016/01/connect-mac-iphone-to-simple-python.html.
So far I'm able to connect to the server and when I tried to write on the output stream .
let data : NSData = "hello".data(using: String.Encoding.utf8)! as NSData
outStream?.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)
I got error on write(UnsafePointer(data.bytes), ...
Cannot convert value of type 'UnsafeRawPointer' to expected argument type 'RawPointer'
Related
I am creating a windows UDP tunnel using wintun driver. I have written a code to receive data from the server and send it to the windows tunnel using the function send_packet and allocatesendpacket. The error I get is that I can read data only as bytes from the UDP server but it causes a mismatch when I pass it to the send_packet function. The error is as follows:
mismatched types
expected struct `wintun::Packet`, found `&[u8]`
Code for send_packet and allocatesendpacket
https://github.com/nulldotblack/wintun/blob/main/src/session.rs
Code for packet struct data type
https://github.com/nulldotblack/wintun/blob/main/src/packet.rs
Link for other dependencies
https://github.com/nulldotblack/wintun
How do I convert the bytes (variable buffer below) to Packet struct data type?. The error of mismatch occurs when I declare the value of a variable packet with the value of the received buffer variable, so that packet variable can be sent to tunnel.
My code:
let socket = UdpSocket::bind("6.0.0.1:8000") //create client socket object with ip and port
.expect("Could not bind client socket");
socket.connect("6.0.0.10:8888") //SERVER IP /PORT
let writer_session = session.clone();
let writer =
std::thread::spawn(move || {
info!("Starting writer");
while RUNNING.load(Ordering::Relaxed) {
let mut buffer = [0u8; 20000];
socket.recv_from(&mut buffer) //get message from server
.expect("Could not read into buffer");
let leng1 = buffer.len();
let mut packet = writer_session.allocate_send_packet(leng1.try_into().unwrap()).unwrap();
packet = &buffer[0..leng1]; //ERROR occurs here
writer_session.send_packet(packet);
}
});
You have two errors the first caused by trying to assign a slice to packet directly which is solved by copying the buffer into packet instead:
packet.bytes_mut().copy_from_slice(&buffer);
The second is that you are not using the length returned by recv_from but instead using the length of the whole buffer which may lead to reading past the end of the read data although memory address is valid. You should do this instead:
let mut buffer = [0u8; 20000];
let (leng1, src_addr) = socket.recv_from(&mut buffer) //get message from server
.expect("Could not read into buffer");
let buffer = &mut buffer[..leng1];
To copy the contents of buffer into packet, you can use slice::copy_from_slice:
packet.bytes_mut().copy_from_slice(&buffer);
I have successfully added https://github.com/chrisballinger/Opus-iOS to my project and I am able to call the functions declared in its header.
I want to convert from OPUS to AAC so my first step would be to decode my opus file. However, it keeps throwing an error code.
The file I am using is the 2-second file from https://people.xiph.org/~giles/2012/opus/.
This is my code
let url = Bundle.main.url(forResource: "detodos", withExtension: "opus")
print(url) //prints path correctly
var bytes = [UInt8]()
if let data = NSData(contentsOf: url!) {
var buffer = [UInt8](repeating: 0, count: data.length)
data.getBytes(&buffer, length: data.length)
bytes = buffer
let d = opus_decoder_create(48000, 1, nil)
var sampleBuffer = [opus_int16](repeating: 0, count: data.length)
print(opus_int32(bytes.count)) //6270
let w = opus_decode(d!, bytes, opus_int32(bytes.count), &sampleBuffer, opus_int32(5760), opus_int32(1))
print(sampleBuffer) // [0,0,...] every time
print(w) //-4 every time
//-4 = OPUS_INVALID_PACKET
}
I would've guessed that in this very minimal implementation nothing should go wrong but apparently it does. Printing my bytes object returns tons of different numbers so I know for a fact it doesn't stay at all-0's.
I realized that it might be due to the method expecting pure "audio data" but the file also contains a header etc. How can I strip this off?
The opus library decodes Opus packets. You give it an Opus packet and it decodes it; one packet at a time. You are trying to give it an entire Ogg Opus file, including all of the headers, framing, tags, and other metadata.
The easiest way to decode an entire Ogg Opus file is with the opusfile library. It can even stream the data from a URL if you want, so that you don't have to download it all before you start decoding as you are doing here. Alternatively, instead of opusfile you could use the ogg library to extract packets from the file and then pass each audio packet to the opus library for decoding.
I'm trying to use the example where a file is uploaded using NSFileHandle. I get the following compile errors:
I get this 2 times:
Cannot invoke 'uploadSessionStart' with an argument list of type '(input: NSData?)'
I get the errors once in uploadFirstChunk() and once in uploadNextChunk(), both times in this statement:
var data : NSData? = nil
...
data = fileHandle!.readData(ofLength: chunkSize) as NSData?
...
dbClient.files.uploadSessionStart(input: data)<==
I also get this error in uploadNextChunk():
Type of expression is ambiguous without more context
This is the statement where it occurs:
let destPath = "/MDG/test/Test1.mp4"
...
dbClient.files.uploadSessionFinish(
cursor: Files.UploadSessionCursor(sessionId: self.sessionId, offset: UInt64(offset)),
commit: Files.CommitInfo(path: destPath),<==
input: data!)
I'm working on a solution to send commands to a point of sale receipt printer and having some issues getting the command format right. Ive got a socket open to the device and thats working, because incorrect commands are printed. What the SPEC calls for in this command is to send the following:
1B 07 or in decimal 27 7. Which in ASCII is ESC_KEY BEL. The only example the spec shows is for .NET:
MSComm1.Output = Chr$(&H1B) & Chr$(&H07)
What I've been trying:
// Socket is open previously using CFStreamCreatePairWithSocketToHost.
var cmd = "27 07"
if let dataString = "\(cmd)\r".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false), let oStream = self.outputStream {
self.outputData.append(dataString)
if oStream.hasSpaceAvailable {
oStream.write(UnsafePointer((self.outputData.first! as NSData).bytes), maxLength: self.outputData.first!length)
}
}
The data is getting there, but I think the format of the message is wrong. Any help would be appreciated.
Just create a byte (aka UInt8) array with the data that you want
to send, and pass that directly to the write() method of NSOutputStream:
let cmd: [UInt8] = [0x1B, 0x07]
oStream.write(cmd, maxLength: cmd.count)
Note that you send bytes to the output stream, not hex data.
It makes not difference at all if you create the array with hexadecimal
integer literals as above, or as
let cmd: [UInt8] = [27, 7]
the data is exactly the same.
I'm trying to do some simple encoding using NSInputStream and NSOutputStream:
import Foundation
let path = "/Users/johni/desktop/a" // holds "123456789abcdef"
var data: NSData = NSData(contentsOfFile: path)
var inp: NSInputStream = NSInputStream(data: data)
println(data.length) // returns 15
println(inp.hasBytesAvailable) // returns false
I'm receiving a -1 from the read method, meaning that it has no bytes available, why does this happen?
I have also have tried initializing the NSInputStream directly with the fileAtPath initializer and got the same error.
You can't use an input stream until you open it.
inp.open()
inp.hasBytesAvailable //returns true