当前位置: 动力学知识库 > 问答 > 编程问答 >

Send a tcp request from PHP Website to JAVA program

问题描述:

I want to send a TCP Request from my website to my java application. So my java application should be able to receive a JSON array and print it.

I searched around for a few hours, but I could not find a solution.

Here is, what I have in PHP:

<?php

$array = array(

0 => "test",

1 => "test1"

);

json_encode($array);

$host = "tcp://localhost";

$port = 8123;

$data = json_encode($array);

$errstr = '';

$errno = '';

if ( ($fp = fsockopen($host, $port, $errno, $errstr, 3) ) === FALSE)

echo "$errstr ($errno)";

else {

print 'SUCCESS!<br />';

fwrite($fp, $data);

while (! feof($fp)) {

echo fgets($fp, 4096);

}

fclose($fp);

}

My Java code:

public class tcp {

public static void main(String argv[]) throws Exception {

String clientSentence;

String capitalizedSentence;

ServerSocket welcomeSocket = new ServerSocket(8123);

while (true) {

Socket connectionSocket = welcomeSocket.accept();

BufferedReader inFromClient =

new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

clientSentence = inFromClient.readLine();

System.out.println("Received: " + clientSentence);

capitalizedSentence = clientSentence.toUpperCase() + '\n';

outToClient.writeBytes(capitalizedSentence);

connectionSocket.close();

}

}

}

So as you should see, I never have done something like this before.

My questions:

1) Do I have to open port "8123", also when the website and my application will run on localhost (ubuntu / debian)? -> how should I open them correctly?

2) When I start my app, I think I have to create the "tcp" java object. -> tcp tcp = new tcp - is this enough or do I have to call a method other something similar?

3) What do I have to change in my code? The Application does just nothing when I send a request...

So I hope you guys can help me with my problem :)

Greets

EDIT:

When I try to run my PHP script, I git following error:

Warning: fsockopen(): unable to connect to tcp://localhost:8123 (Connection refused) in /PATH_TO_PHP/TCPSEND/index.php on line 16

Connection refused (111)

分享给朋友:
您可能感兴趣的文章:
随机阅读: