2013-01-02 209 views
9

我需要從php客戶端向java服務器發送信息,但服務器端沒有收到任何信息,儘管一個打印語句在服務器上成功執行,客戶端文本無法接收服務器端。下面是代碼:java和php之間的簡單客戶端服務器通信

Java服務器:

import java.io.BufferedReader; 
import java.net.*; 
import java.io.*; 

public class javaphp2 { 
    private static ServerSocket socket; 

    private static Socket connection; 
    private static String command  = new String(); 
    private static String responseStr = new String(); 

    private static int port = 4309; 

    public static void main(String args[]) { 
     System.out.println("Signal Server is running."); 

     try { 
      socket = new ServerSocket(port); 

      while (true) { 
       connection = socket.accept(); 

       InputStreamReader inputStream = new InputStreamReader(connection.getInputStream()); 
       DataOutputStream response = new DataOutputStream(connection.getOutputStream()); 
       BufferedReader input = new BufferedReader(inputStream); 

       command = input.readLine(); 
       //System.out.println("The input is" + command); 
       response.writeBytes(responseStr); 
       response.flush(); 
       //response.close(); 

       System.out.println("Running"); 
      } 
     } catch (IOException e) { 
      System.out.println("Fail!: " + e.toString()); 
     } 

     System.out.println("Closing..."); 
    } 
} 

PHP客戶:

#!/usr/local/bin/php -q 
<?php 
$address = '132.119.90.165'; 
$port = 4309; 

$socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); 
socket_connect($socket, $address, $port); 

$message = 'Apple'; 
$len = strlen($message); 

$status = socket_sendto($socket, $message, $len, 0, $address, $port); 
if($status !== FALSE) 
{ 
    $message = ''; 
    $next = ''; 
    while ($next = socket_read($socket, 4096)) 
    { 
     $message .= $next; 
    } 

    echo $message; 
} 
else 
{ 
    echo "Failed"; 
} 

socket_close($socket); 
?> 

回答

8

得到它!,

我們需要添加$message = "Apple\n";代替$message = 'Apple\n';

0

嘗試將線端添加到您的消息。

$message = 'Apple\n'; 

readLine將始終等待行結束。

+0

謝謝你直到,但同樣的問題... – highlander141

相關問題