gpt4 book ai didi

java - PHP/Java 套接字 - 奇怪的错误?

转载 作者:行者123 更新时间:2023-11-29 03:55:28 24 4
gpt4 key购买 nike

Java代码:

package servermonitor;

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

public class CommandListener extends Thread
{
public int count = 0;
public void run()
{
try
{
ServerSocket server = new ServerSocket(4444);
while(true)
{
System.out.println("listening");
Socket client = server.accept();
System.out.println("accepted");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("got reader");
String data = "";
String line;
while((line = in.readLine()) != null)
{
System.out.println("inloop");
data = data + line;
}
System.out.println("RECIEVED DATA: " + data);
in.close();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
count++;
out.write("gotcha: " + count + "\\n");
out.flush();
}

}
catch(IOException ex)
{
System.out.println(ex.getMessage());
}

}

}

Java 控制台(当我访问以下 PHP 脚本时):

listening
accepted
got reader

PHP代码:

<?php
$PORT = 4444; //the port on which we are connecting to the "remote" machine
$HOST = "localhost"; //the ip of the remote machine (in this case it's the same machine)

$sock = socket_create(AF_INET, SOCK_STREAM, 0) //Creating a TCP socket
or die("error: could not create socket\n");

$succ = socket_connect($sock, $HOST, $PORT) //Connecting to to server using that socket
or die("error: could not connect to host\n");

$text = "Hello, Java!\n"; //the text we want to send to the server

socket_write($sock, $text, strlen($text) + 1) //Writing the text to the socket
or die("error: failed to write to socket\n");

$reply = socket_read($sock, 10000) //Reading the reply from socket
or die("error: failed to read from socket\n");

echo $reply;
?>

当我导航到 PHP 页面时,它会一直加载。

有什么想法吗?

最佳答案

Java 端期望在其输入中有一个换行符。你没有发送一个,所以 readLine 永远不会完成。

此外,readLine 在套接字关闭或发生异常(例如 I/O 错误)之前不会返回 null。如果您的协议(protocol)是这样工作的,您需要在读取一行后立即返回一些数据。

关于java - PHP/Java 套接字 - 奇怪的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6659760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com