我在 php 中打开一个套接字并发送一条消息。当我尝试在此套接字中读取 Java 中的消息时,连接已建立但消息为空?
有什么帮助吗?无法使用 PHP 客户端从 Java 套接字服务器读取响应这是我遇到的相同问题,但我确实将 \n 放入消息中。
// 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";
和java端
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);
Java 代码的运行类似于服务器的网关。