简体   繁体   中英

Java TCP socket server with PHP client?

Hey there ,

I am developing an TCP socket server in Java. The client(s) must connect to a webpage (in PHP)

Well, here come's my trouble.. They can connect to the specified host, but the server can't read the packets that the client send.

If I create the client in Java, it works 100%. Well, here are some snippets of my code. I hope someone have a answer for me. Because I'm stuck.

This is my little PHP script that sends:

<?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;
?>

The socket side is:

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;
}

}

And this little code connects to the PacketHandler: PacketHandler ph = new PacketHandler();

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

            outputLine = ph.processInput(inputLine);

            out.println(outputLine);
        }

As you are using readLine on your input stream so make sure your clients are sending the data with linefeed.

From the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM