我试图在Java服务器和PHP客户端之间创建套接字通信。我唯一得到的是连接,但从PHP客户端收到的奇怪的消息(凌乱的代码)。 以下是有关Java服务器的代码:
public class TestServer extends Thread {
private ServerSocket serverSocket;
public TestServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
public void run() {
while (true) {
try {
System.out.println("Waiting for client on port " + serverSocket.getLocalPort()
+ "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
InputStreamReader inputStream = new InputStreamReader(server.getInputStream());
BufferedReader input = new BufferedReader(inputStream);
DataOutputStream response = new DataOutputStream(server.getOutputStream());
String command = input.readLine();
System.out.println(command);
server.close();
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String[] args) {
int port = Integer.parseInt(args[0]);
try {
Thread t = new TestServer(port);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
PHP客户端中的代码:
<?php
$ip="192.168.1.6"; //Set the TCP IP Address to connect too
$port="9999"; //Set the TCP PORT to connect too
//Connect to Server
$socket = stream_socket_client("tcp://{$ip}:{$port}", $errno, $errstr, 30);
if($socket) {
//Start SSL
stream_set_blocking ($socket, true);
stream_socket_enable_crypto ($socket, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT);
stream_set_blocking ($socket, false);
$command = array("autospray", "on");
$sock= $socket;
$msg = $command;
function write(&$sock,$msg) {
//$msg = "$msg\n\0";
$length = strlen($msg);
while(true) {
$sent = @socket_write($sock,$msg."\n" ,$length) or die("Could not write output\n");
@socket_shutdown($sock, 2);
@socket_close($sock);
if($sent === false) {
return false;
}
if($sent < $length) {
$msg = substr($msg, $sent);
$length -= $sent;
print("Message truncated: Resending: $msg");
} else {
return true;
}
}
return false;
}
}
?>
答案 0 :(得分:0)
在PHP中,您使用:stream_socket_enable_crypto()加密套接字,因此JAVA服务器将在inputStream中接收加密流。 您需要解密流才能获得真实的消息。