3

I'm trying to send messages between Java and PHP using sockets, but I can't get it to work. I firstly tried Java to Java and that's working fine, but now I want to get PHP to Java and otherwise. The PHP said that the message was sent but Java don't get one. Could anyone help me with this?

Java server:

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public static void main(String args[]) throws IOException {
        final int portNumber = 81;
        ServerSocket serverSocket = new ServerSocket(portNumber);
        while (true) {
            Socket socket = serverSocket.accept();
            OutputStream os = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(os, true);

            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println("Client response: " + line);
                pw.println(line);
            }
            pw.close();
            br.close();
            os.close();
            socket.close();
        }
    }
}

Java client:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client extends Thread {

    Socket socket;
    BufferedReader br;
    PrintWriter out;

    String disconnectReason;
    boolean disconnected = false;
    public boolean running;

    public static void main(String[] args) {
        Client client = new Client();
        client.sendMessage("Hello!");
    }

    public Client() {
        new Thread(this).start();
        running = true;
    }

    @Override
    public void run() {
        try {
            socket = new Socket("localhost", 81);
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            while (running) {
                String line;
                if((line = br.readLine()) != null) {
                    System.out.println("Server response: " + line);
                }
            }
            System.out.println("Disconnected. Reason: " + disconnectReason);
            disconnected = true;
            running = false;
            br.close();
            out.close();
            socket.close();
            System.out.println("Shutted down!");
            System.exit(0);
        } catch (IOException e) {
            if(e.getMessage().equals("Connection reset")) {
                disconnectReason = "Connection lost with server";
                disconnected = true;
                System.out.println("Disconnected from server. Reason: Connection reset");
            } else {
                e.printStackTrace();
            }
        }
    }

    public void sendMessage(String message) {
        if(running) {
            if (!disconnected) {
                if (out != null && socket != null) {
                    out.println(message);
                    out.flush();
                }
            }
        }
    }
}

PHP Code that i tried:

<?php
$host = "localhost"; 
$port = 81;
$data = 'test';

if ( ($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === FALSE )
    echo "socket_create() failed: reason: " .             socket_strerror(socket_last_error());
else 
{
    echo "Attempting to connect to '$host' on port '$port'...<br>";
    if ( ($result = socket_connect($socket, $host, $port)) === FALSE )
        echo "socket_connect() failed. Reason: ($result) " .     socket_strerror(socket_last_error($socket));
    else {
        echo "Sending data...<br>";
        socket_write($socket, $data, strlen($data));
        echo "OK<br>";

        echo "Reading response:<br>";
        while ($out = socket_read($socket, 2048)) {
            echo $out;
        }
    }
    socket_close($socket);      
}
?>

EDIT: Seems that commenting socket_read fixes the problem with receiving the message in Java, but still the problem remains how I can send from Java to PHP

5
  • i've commented the socket_read line in php and it was successful, the test received and printed in java console. Commented Mar 26, 2017 at 17:38
  • @MaMadLord ah, but how can I read the messages that I send from Java to PHP? Commented Mar 26, 2017 at 17:44
  • ok i found the receiving problem, you need to determine where is the end of your line with "\r\n" like initialize $data with "test\r\n" but still i don't know what is the reading problem. Commented Mar 26, 2017 at 17:53
  • 1
    Oh well that fixed it, thanks. PHP is receiving my data from Java also now. Commented Mar 26, 2017 at 17:57
  • yeah the problem was that i'd change your code a bit :)) Commented Mar 26, 2017 at 17:58

1 Answer 1

3

ok found the problem, you have to show where is the end of the line in php so the socket could send it, and it will work like a charm :)

 socket_write ($my_socket, $data."\r\n", strlen ($data."\r\n"));
Sign up to request clarification or add additional context in comments.

Comments

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.