Java TCP套接字服务器与PHP客户端?

3

你好,

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

问题来了,他们可以连接到指定的主机,但服务器无法读取客户端发送的数据包。

如果我在Java中创建客户端,它可以完美运行。下面是我的一些代码片段。希望有人能为我解答,因为我被卡住了。

这是我发送数据的小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;
?>

套接字的一侧是:
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);
        }
1个回答

2
由于您正在使用输入流上的readLine方法,请确保您的客户端发送的数据包含换行符。
javadocs中可以得知:

readLine()方法读取一行文本。一行被认为是以换行符('\n')、回车符('\r')或者回车符后紧跟着换行符终止的。


那他应该如何修复呢? - wouterdz
1
在我的输入行中添加 \n 不起作用。我真的,真的卡住了。 - Merijn K

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接