带有 PHP 客户端的 Java TCP 套接字服务器?

标签 java php sockets tcp

你好

我正在用 Java 开发一个 TCP 套接字服务器。客户端必须连接到网页(PHP)

好吧,我的麻烦来了..他们可以连接到指定的主机,但是服务器无法读取客户端发送的数据包。

如果我用 Java 创建客户端,它可以 100% 工作。好吧,这是我的代码的一些片段。我希望有人能为我解答。因为我卡住了。

这是我发送的小 PHP 脚本:

<?php

set_time_limit(0);

$PORT = 1337; //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 = "wouter123"; //the text we want to send to the server

 socket_sendto($sock, $text, strlen($message), MSG_EOF, '127.0.0.1', '1337');
//socket_write($sock, $text . "\n", strlen($text) + 1) //Writing the text to the socket
 //      or die("error: failed to write to socket\n");



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


echo $reply;
?>

socket 端是:

package com.sandbox.communication;

public class PacketHandler {

public String processInput(String theInput) {
    String theOutput = null;

    if (theInput == "wouter123") {
        theOutput = theInput;
    }else {
        theOutput = "Cannot find packet. The output packet is " + theInput;
    }

    return theOutput;
}

这段小代码连接到 PacketHandler: PacketHandler ph = new PacketHandler();

        while ((inputLine = in.readLine()) != null)
        {

            outputLine = ph.processInput(inputLine);

            out.println(outputLine);
        }

最佳答案

当您在输入流上使用 readLine 时,请确保您的客户端使用换行符发送数据。

来自javadocs

readLine() Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

关于带有 PHP 客户端的 Java TCP 套接字服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16647258/

相关文章:

ios - “Tried connecting on an already connected socket”-Socket.IO-客户端-Swift

java - @Autowired-ing DAO 时出现 ValidationException

java - 从 .pem 文件加载私钥时出现无效 key 格式异常

php - 如何重定向用户而不是 Google(和其他抓取工具)?

php - 在多边形 PHP 中查找点

PHP pg_query 没有执行

linux - 我可以通过远程安装 .X11-unix 来与 X 服务器通信吗?

java - 让套接字等待来自 JTextArea 的输入

java - 在java中改变图像颜色

java - 致命异常 : main and Null pointer exception arise while running a simple android program