如何通过java服务器套接字将多个对象发送到php套接字?
问题描述:
I am trying to send multiple objects through a php socket from a java server. Although when i try to send 2 or more json objects to php client, the website just refuses to load. But when i send only one json object, it seems to work fine.
This is the code from my java server:
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();
}
}
}
and this is what the php looks like:
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()) . "
";
} else {
// echo "OK.
";
}
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo "socket_connect() failed.
Reason: ($result) " . socket_strerror(socket_last_error($socket)) . "
";
} else {
// echo "OK.
";
}
do{
$obj = socket_read($socket, 1024);
if($obj == 'END'){
break;
}
array_push($recieved, json_decode($obj));
}while(true);
socket_close($socket);
return $recieved;
}
答
I haven't tried this, but out of instinct I would suggest to send a JSONArray with the 2 (or more) JSONObjects inside, and in the PHP side of stuff, assume that you recieve an array, instead of many objects.