Edit: I've solved my own problem and fixed the code below to reflect those changes in case anyone runs into the same difficulties. This code will work for a PHP client and java server connection.
I know the forums are peppered with these questions...however, I have tried nearly everything else for over eight hours and am at my wit's end. I am trying to send a string from a java Socket to a PHP Socket. I'm a PHP socket newbie so hopefully someone can diagnose my problem rather easily... Here is the PHP code:
<html>
<head>
</head>
<body>
<?php
//connection to NetworkService in app to manage incoming request
$addr = 'your server address';
$port = 1740;
$socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
socket_connect($socket, $addr, $port);
//"
" is very important as it signifies to the server
// that this is the end of the transmission
$request = "message to send
";
//no flags needed circa php 5.2
$sent = socket_sendto($socket, $request, strlen($request), 0 , $addr, $port);
if($sent !== FALSE){
$message = '';
$next = '';
//loop through to continue appending until everything has been read
while($next = socket_read($socket, 4096)){
$message .= $next;
}
echo $message;
} else{
echo "Failed.";
}
socket_close($socket);
?>
</body>
</html>
Java Code:
public class TestServer{
public static void main(String argv[0]) throws Exception{
String in; String out = "Hello PHP
";
ServerSocket inSock = new ServerSocket(1740);
while(true){
System.out.println("Now accepting connections");
Socket outSock = inSock.accept();
BufferedReader bReader = new BufferedReader(
new InputStreamReader(outSock.getInputStream()));
PrintWriter sender = new PrintWriter(outSock.getOutputStream());
in = bReader.readLine();
System.out.println("Received: " + in);
dWriter.print(out);
System.out.println("Sent: " + out);
}
}
}
The problem is not with the first send (from PHP to JAVA) but with the second one (the response) which just hangs. The Java code runs completely so I know the problem has to do with the socket_read() or socket_recv() functions. I have tried to sleep() and tried a method using socket_setnoblock() (though perhaps incorrectly). As you can see by my "OPTION:" comments, I have tried a few different methods here as well but to no avail. What could I be missing? Thank you so much in advance!