我正在尝试在Java中的SocketServer(服务器)和php中的Socket(客户端)之间建立通信。 客户端能够连接到主机,客户端能够发送消息,服务器成功读取消息。但是当 SocketServer写入客户端时,问题出现,客户端没有收到来自服务器的消息。
我已经阅读了同一场景中的其他问题(java-php套接字通信),但我似乎无法找到导致问题的原因。
如果我使用Java Socket作为客户端,那么通信就可以完全兼顾。
服务器:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
protected ServerSocket socket;
protected final int port = 9005;
protected Socket connection;
protected String command = new String();
protected String responseString = new String();
public void init(){
System.out.println( "Launching Server: " );
try{
socket = new ServerSocket(port);
while(true)
{
// open socket
connection = socket.accept();
System.out.println( "Client Connected " );
// get input reader
InputStreamReader inputStream = new InputStreamReader(connection.getInputStream());
BufferedReader input = new BufferedReader(inputStream);
// get input
command = input.readLine();
// process input
System.out.println("Command: " + command);
responseString = command + " MC2 It Works!";
// get output handler
PrintStream response = new PrintStream(connection.getOutputStream());
// send response
response.println(responseString);
}
}
catch (IOException e){
e.printStackTrace();
}
}
}
客户:
class Client {
private $address;
private $port;
public function __construct($address, $port){
$this->address = $address;
$this->port = $port;
$this->init();
}
private function init(){
//create socket
if(! $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'))){
$this->showError("socket create");
};
//establish connection
socket_connect($socket, $this->address, $this->port);
//write to server
$message = "I am a client";
socket_write($socket, $message, strlen($message)); //Send data
echo "Listening to Server\n";
//read from server
if(!$reponse = socket_read($socket, 2048, PHP_NORMAL_READ)){
$this->showError("socket read");
}
//print response
echo "Response from server------------------\n";
echo $reponse;
socket_close($socket);
}
private function showError($message){
echo ("Error: ".$message);
exit(666);
}
}
$address="localhost";$port=9005;
echo "Testing Client Server\n";
$client = new Client($address, $port);
有人可以指导我这里可能出现的问题吗?
答案 0 :(得分:0)
在服务器端,代码需要一行(以换行符终止),在php中发送
socket_write($socket, $message, strlen($message));
请检查您发送的数据,确保发送换行符。