I open a socket in php and i send a message. When I try to read the message in Java in this socket the connection is established but the message is null?
Any help? Cannot read response from Java socket server using PHP client this is the same problem i have but i do put \n in the message.
// variables
$host = gethostbyname('localhost');
$port = 4444;
$message = $host." list\n\0";
// create socket
if (!($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created!\n";
// connect
if (!socket_connect($sock, $host, $port)) {
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't connect: [$errorcode] $errormsg \n");
}
echo "Connection established!\n";
echo $message;
$length = strlen($message);
// get room info - send message
while(true){
$sent=sock_write($sock, $message, 1024);
if ($sent===false) {
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't send data: [$errorcode] $errormsg \n");
}
// Check if the entire message has been sented
if ($sent < $length) {
// If not sent the entire message.
// Get the part of the message that has not yet been sented as message
$st = substr($msg, $sent);
$message= $st;
// Get the length of the not sented part
$length -= $sent;
} else {
break;
}
}
echo "Message sent!\n";
and the java side
while (true) {
try {
socket = new ServerSocket(4444);
} catch (UnknownHostException e) {
System.err.println("Dont know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to localhost");
System.exit(1);
}
try {
clientSocket = socket.accept();
System.out.printf("Connected!\n");
} catch (IOException e) {
e.printStackTrace();
}
try {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); //object to send data
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); //object to read data
String inputLine, outputLine;
inputLine = in.readLine(); //read data
System.out.println(inputLine);
The Java code operates like a gateway to the server.