Web Server ==> PHP ={ UNIX socket }=> Rust
Make sure socket file read-writable to the PHP / Apache side by chown
-ing the socket.
<?php | |
ini_set('display_errors', 1); | |
$socket = socket_create(AF_UNIX, SOCK_DGRAM, 0); | |
$sockpath = "/path/to/sock"; | |
$request = [ | |
'request' => "{$_SERVER['REQUEST_METHOD']} {$_SERVER['REQUEST_URI']} {$_SERVER['SERVER_PROTOCOL']}", | |
'method' => $_SERVER['REQUEST_METHOD'], | |
'route' => $_SERVER['REQUEST_URI'], | |
]; | |
$jsonized = json_encode($request); | |
$msg_len = pack("J", strlen($jsonized)); | |
var_dump($msg_len); | |
var_dump(strlen($msg_len)); | |
// Send total size | |
$len = socket_sendto($socket, $msg_len, strlen($msg_len), 0, $sockpath, 0); | |
echo "sent length #1 : $len<br/>\n"; | |
// Send actual data | |
$len = socket_sendto($socket, $jsonized, strlen($jsonized), 0, $sockpath, 0); | |
echo "sent length #2 : $len<br/>\n"; | |
echo "<pre>"; | |
print_r($_SERVER); | |
echo "</pre>"; | |
?> |
use std::str; | |
use std::fs; | |
use std::os::unix::net::UnixDatagram; | |
use std::io::prelude::*; | |
fn main() { | |
let sockpath = "/path/to/sock"; | |
fs::remove_file(sockpath).unwrap(); | |
let socket = match UnixDatagram::bind(sockpath) { | |
Ok(sock) => sock, | |
Err(e) => { | |
panic!("Socket cannot be created {:?}", e) | |
} | |
}; | |
loop { | |
// Get packet size first | |
let mut msg_len = [0; 8]; | |
let (count, address) = socket.recv_from(&mut msg_len).unwrap(); | |
let msg_len: u64 = { | |
(msg_len[7] as u64) | |
| ((msg_len[6] as u64) << (8*1)) | |
| ((msg_len[5] as u64) << (8*2)) | |
| ((msg_len[4] as u64) << (8*3)) | |
| ((msg_len[3] as u64) << (8*4)) | |
| ((msg_len[2] as u64) << (8*5)) | |
| ((msg_len[1] as u64) << (8*6)) | |
| ((msg_len[0] as u64) << (8*7)) | |
}; | |
let mut buf = vec![0; msg_len as usize]; | |
let (count, address) = socket.recv_from(&mut buf).unwrap(); | |
let s = match str::from_utf8(&buf) { | |
Ok(v) => v, | |
Err(e) => panic!("Invalid UTF-8 sequence: {}", e), | |
}; | |
println!("Read {} (specified {}), it says: {:?}", count, msg_len, s); | |
} | |
} |