douchensi8625 2015-12-04 21:59
浏览 129

从PHP网站发送tcp请求到JAVA程序

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() + '
';
                    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)
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 #MATLAB仿真#车辆换道路径规划
    • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
    • ¥15 数据可视化Python
    • ¥15 要给毕业设计添加扫码登录的功能!!有偿
    • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
    • ¥15 微信公众号自制会员卡没有收款渠道啊
    • ¥100 Jenkins自动化部署—悬赏100元
    • ¥15 关于#python#的问题:求帮写python代码
    • ¥20 MATLAB画图图形出现上下震荡的线条
    • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘