java:
<code>DataOutputStream <span>out</span> = new DataOutputStream(new BufferedOutputStream(socket<span>.getOutputStream</span>()))<span>;</span><span>out</span><span>.writeInt</span>(<span>"REWQTY"</span><span>.getBytes</span>()<span>.length</span>)<span>;</span><span>out</span><span>.write</span>(<span>"REWQTY"</span><span>.getBytes</span>())<span>;</span><span>out</span><span>.close</span>()<span>;//php端是阻塞的,除非close</span></code>
php:
<code><span><span>function</span><span>readInt</span><span>(<span>$sock</span>)</span> {</span><span>$buf</span> = socket_read(<span>$sock</span>,<span>4</span>); <span>if</span> (<span>$buf</span>){ <span>return</span> unpack(<span>'N'</span>,<span>$buf</span>)[<span>1</span>]; }<span>else</span>{ <span>throw</span><span>new</span><span>Exception</span>(); } } <span><span>function</span><span>readString</span><span>(<span>$socket</span>)</span> {</span><span>$n</span> = readInt(<span>$socket</span>); <span>return</span> socket_read(<span>$socket</span>, <span>$n</span>); } <span>echo</span> readString(<span>$sock</span>,<span>$l</span>); <span>echo</span><span>"\n"</span>;</code>
以上就介绍了PHP socket实现 readInt 和 readString 以及和Java端对接,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。