3

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

How should he fix it then?
Adding a \n to my inputLine doesn't work. I'm really, really stuck.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.