【问题标题】:Java TCP socket server with PHP client?带有 PHP 客户端的 Java TCP 套接字服务器?
【发布时间】:2013-05-14 21:03:44
【问题描述】:

你好

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

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

如果我用 Java 创建客户端,它可以 100% 工作。好吧,这是我的代码的一些 sn-ps。我希望有人能给我一个答案。因为我被困住了。

这是我发送的小 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);
        }

【问题讨论】:

    标签: java php sockets tcp


    【解决方案1】:

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

    来自javadocs

    readLine() 读取一行文本。一条线被认为是终止的 由换行符 ('\n')、回车符 ('\r') 或 回车后紧跟换行符。

    【讨论】:

    • 那他应该怎么修呢?
    • 向我的 inputLine 添加一个 \n 不起作用。我真的,真的被困住了。
    猜你喜欢
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 2017-07-10
    • 2012-06-05
    相关资源
    最近更新 更多