PHP / Java套接字通信无法正常工作
发布时间:2020-12-13 15:56:22 所属栏目:PHP教程 来源:网络整理
导读:我遇到了以下问题已经被困了两天:我写了一个 java套接字服务器,可以接收和发送数据到’localhost:64005’托管的套接字.我可以通过 PHP连接到它并发送或接收消息.但是我不能发送然后收到答案.我已经将问题追溯到我编写的php脚本. ?php class socketCommunic
我遇到了以下问题已经被困了两天:我写了一个
java套接字服务器,可以接收和发送数据到’localhost:64005’托管的套接字.我可以通过
PHP连接到它并发送或接收消息.但是我不能发送然后收到答案.我已经将问题追溯到我编写的php脚本.
<?php class socketCommunication{ protected $PK; protected $ip = '127.0.0.1'; protected $port = 64005; protected $socket; public $result; function __construct($key){ $this->socket = socket_create(AF_INET,SOCK_STREAM,0) or die("Could not create socketn"); $this->result = socket_connect($this->socket,$this->ip,$this->port) or die("Could not connect to servern"); $this->PK = $key; $this->sendSocket(); } function getResponse(){ //$input = socket_read($this->socket,1024) or die("Could not read"); $bytes = socket_recv($this->socket,$buf,2048,MSG_WAITALL); return $buf; } function sendSocket(){ $len = strlen($this->PK); socket_send ($this->socket,$this->PK,$len,0); } } ?> <?php //include("/mysql/RandomQuery.php"); include("/java/socketCommunication.php"); $object2 = new socketCommunication(100001); echo $object2->getResponse(); ?> java套接字服务器: package Server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.concurrent.Semaphore; import Database.Reader; public class Receive implements Runnable { Semaphore semaphore; private Socket connection; String result = "default"; public Receive(Socket conn,Semaphore sem){ this.connection = conn; this.semaphore = sem; } @Override public void run() { try { semaphore.acquire(); System.out.println(connection.toString()); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); PrintWriter out = new PrintWriter(connection.getOutputStream(),true); String userInput; while ((userInput = in.readLine()) != null) { System.out.println(userInput); Reader reader = new Reader(Integer.parseInt(userInput)); this.result = reader.getResult(); System.out.println(result); out.println(result); break; } connection.close(); in.close(); System.out.println("input is closed"); semaphore.release(); } catch (IOException | InterruptedException e) {e.printStackTrace();} } } 一旦我在php中调用sendSocket和getResponse方法,页面就会无限加载.但是,如果我只是调用sendSocket或getResponse(在更改java套接字之后它不会等待输入)方法,它们可以正常工作. 我究竟做错了什么? 亲切的问候. 解决方法
见:
http://php.net/manual/en/function.socket-recv.php
MSG_WAITALL标志将阻塞,直到它收到缓冲区的全长.您指定为2048字节的数据. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |