我正在尝试从java服务器通过php套接字发送多个对象。 虽然当我尝试向php客户端发送2个或更多json对象时,该网站只是拒绝加载。但是当我只发送一个json对象时,它似乎工作正常。
这是我的java服务器的代码:
package org.articron.server;
import org.json.simple.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
/**
* @author Articron | Arno
* on 8-8-2015.
*/
public class TCPConnection implements Runnable {
private Socket client;
private PrintWriter writer;
private BufferedReader reader;
private JSONObject tosend;
private JSONObject tosend2;
public TCPConnection(Socket client, PrintWriter writer, BufferedReader reader) {
this.client = client;
this.writer = writer;
this.reader = reader;
tosend = new JSONObject();
tosend2 = new JSONObject();
tosend.put("scriptid","2");
tosend.put("name","mathias@cochet.lol");
tosend2.put("scriptid","1");
tosend2.put("botname","arno.gerver@gmail.com");
}
@Override
public void run() {
try {
tosend.writeJSONString(writer);
tosend2.writeJSONString(writer);
writer.write("END");
writer.flush();
writer.close();
reader.close();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这就是php的样子:
function dataTrans()
{
$recieved = array();
/* Get the port for the WWW service. */
$service_port = 5678;
/* Get the IP address for the target host. */
$address = gethostbyname('104.251.212.75');
/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
// echo "OK.\n";
}
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
// echo "OK.\n";
}
do{
$obj = socket_read($socket, 1024);
if($obj == 'END'){
break;
}
array_push($recieved, json_decode($obj));
}while(true);
socket_close($socket);
return $recieved;
}
答案 0 :(得分:0)
我还没试过这个,但出于本能,我建议发送一个带有2个(或更多)JSONObjects的JSONArray,并且在PHP方面,假设你收到一个数组,而不是许多物品。