我需要创建Java套接字客户端和PHP-cli套接字服务器,并且需要向客户端发送一个UTF-8编码的字节数组,并使Java BufferedInputStream.read()函数接受它。
[SERVER]
$input = socket_read($client[$i]['sock'],1024,PHP_BINARY_READ);
if($input==null || $input===FALSE) {unset($client[$i]);}
socket_write($client[$i]['sock'], unpack('C*', utf8_encode($input)));
[CLIENT]
out = new BufferedOutputStream(socket.getOutputStream());
out.write(str.getBytes("UTF-8"));
out.flush();
in = new BufferedInputStream(socket.getInputStream());
byte[] b = new byte[]{};
str = new String(in.read(b), "UTF-8");
System.out.println("[SOCKET] Server: " + str);
所以我需要PHP的类比
String.getBytes("UTF-8");
感谢您的反馈!
答案 0 :(得分:0)
更改输入流。这解决了我的问题。尝试更改规则:
in = new BufferedInputStream(socket.getInputStream());
要:
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
在PHP端,您可以使用utf8_encode
将String编码为UTF-8。 E.g。
$message = utf8_encode($message);
if ( ($fp = fsockopen($host, $port, $errno, $errstr, 3) ) === FALSE)
echo "$errstr ($errno)";
else {
print 'SUCCESS!<br />';
fwrite($fp, $message);