首页 \ 问答 \ 使用Socket的PHP到Java(PHP to Java using Socket)

使用Socket的PHP到Java(PHP to Java using Socket)

我正在尝试使用套接字在Java和PHP之间发送消息,但我无法让它工作。 我首先尝试使用Java来实现Java,并且工作正常,但现在我希望将PHP转换为Java等。 PHP说消息已发送但Java没有收到。 任何人都可以帮我这个吗?

Java服务器:

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客户端:

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代码:

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

编辑:似乎注释socket_read修复了在Java中接收消息的问题,但问题仍然是我如何从Java发送到PHP


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


原文:https://stackoverflow.com/questions/43032116
更新时间:2023-06-12 17:06

最满意答案

您不应该修复JTextArea的大小。 而是通过调用具有体面的列和行号参数的构造函数来初始化它,并将其放入JScrollPane中,这样如果文本增加,则不会丢失文本。


You shouldn't fix the size of a JTextArea. Rather initialize it by calling its constructor with decent column and row number parameters, and put it in a JScrollPane so if the text increases, you'll not lose the text.

相关问答

更多
  • 尝试调用pack()两次。 JTextArea有一些奇怪的行为,如Java错误数据库中此条目中所述 。 它首先将其首选大小报告为非常宽的单行条目(例如,一行,一千列)。 一旦它意识到它具有一定的宽度,它就会根据需要的行数报告正确的首选大小。 为了解决这个问题,我必须做很多不同的事情,包括继承JTextArea并修改它的行为有点聪明。 在这种情况下,Double pack()可能适用于您,或者您可能不得不求助于更复杂的调整,具体取决于布局中的所有内容如何组合在一起。 Got it to work .. Ros ...
  • 但我只能接受一行输入 单行文本区域显示了如何执行此操作。 相关代码是 textArea.getDocument().putProperty("filterNewlines", Boolean.TRUE); but I can only accept one line of input Single Line Text Area shows how you can do this. The relevant code is textArea.getDocument().putProperty("filter ...
  • 在JTextArea的父容器中(在图形中表示为Panel 1),调用函数: panel1.setLayout(new BorderLayout()); 供参考,请参阅此文档页面: https://docs.oracle.com/javase/7/docs/api/java/awt/BorderLayout.html 由于panel1中只有一个子节点,因此panel1的BorderLayout布局管理器将默认拉伸文本区域以使用父容器中的所有可用空间。 您可能想要删除指定TextArea大小的构造函数参数。 ...
  • 您可以将JTextArea放在BorderLayout的北部,例如 contentPane.setLayout(new BorderLayout()); contentPane.add(textArea, BorderLayout.NORTH); 然后它将根据需要使用尽可能多的空间。 注意:如果需要换行,请不要忘记textArea.setLineWrap(true); 。 You can just put the JTextArea in the north part of a BorderLayout, ...
  • 由于每个系统都可以以不同的方式渲染字体,因此应尽可能避免使用像素测量 相反,请提供您想要显示的行和列 JTextArea ta = new JTextArea(5, 20); Because each system can render fonts differently, you should avoid using pixel measurements where possible Instead, provide the rows and columns you want to display JT ...
  • 您不应该修复JTextArea的大小。 而是通过调用具有体面的列和行号参数的构造函数来初始化它,并将其放入JScrollPane中,这样如果文本增加,则不会丢失文本。 You shouldn't fix the size of a JTextArea. Rather initialize it by calling its constructor with decent column and row number parameters, and put it in a JScrollPane so if t ...
  • 不要将文本区域添加到框架中。 this.add(input); 相反,您需要将包含文本区域的JScrollPane添加到框架中: this.add(new JScrollPane(input)); Don't add the text area to the frame. this.add(input); Instead you need to add a JScrollPane containing the text area to the frame: this.add(new JScrol ...
  • 你可以使用textfeld.setBounds(int allignmentX,int allignmentY,int height,int width); 设置JTextArea的边界。 You can use textfeld.setBounds(int allignmentX, int allignmentY, int height, int width); to set the bounds of the JTextArea.
  • 您的组件很可能在布局管理器的控制之下。 您可以建议更改大小的唯一方法是使用setColumns和setRows并使用一个布局管理器来考虑其组件的首选大小 import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.Actio ...
  • 将JTextArea行或列设置为所需的首选大小。 如果一个人拥有另一个身高,那么就要给它一半的行数。 此外,您的布局GridLayout将忽略行计数,而是使所有组件保持相同的大小,基本上是容纳所有组件的最大大小。 而是使用更好的布局管理器,例如BoxLayout。 例如, // this.setLayout(new GridLayout(ROWS_IN_THIS_GRID, COLUMNS_IN_THIS_GRID)); setLayout(new BoxLayout(this.getContent ...

相关文章

更多

最新问答

更多
  • h2元素推动其他h2和div。(h2 element pushing other h2 and div down. two divs, two headers, and they're wrapped within a parent div)
  • 创建一个功能(Create a function)
  • 我投了份简历,是电脑编程方面的学徒,面试时说要培训三个月,前面
  • PDO语句不显示获取的结果(PDOstatement not displaying fetched results)
  • Qt冻结循环的原因?(Qt freezing cause of the loop?)
  • TableView重复youtube-api结果(TableView Repeating youtube-api result)
  • 如何使用自由职业者帐户登录我的php网站?(How can I login into my php website using freelancer account? [closed])
  • SQL Server 2014版本支持的最大数据库数(Maximum number of databases supported by SQL Server 2014 editions)
  • 我如何获得DynamicJasper 3.1.2(或更高版本)的Maven仓库?(How do I get the maven repository for DynamicJasper 3.1.2 (or higher)?)
  • 以编程方式创建UITableView(Creating a UITableView Programmatically)
  • 如何打破按钮上的生命周期循环(How to break do-while loop on button)
  • C#使用EF访问MVC上的部分类的自定义属性(C# access custom attributes of a partial class on MVC with EF)
  • 如何获得facebook app的publish_stream权限?(How to get publish_stream permissions for facebook app?)
  • 如何防止调用冗余函数的postgres视图(how to prevent postgres views calling redundant functions)
  • Sql Server在欧洲获取当前日期时间(Sql Server get current date time in Europe)
  • 设置kotlin扩展名(Setting a kotlin extension)
  • 如何并排放置两个元件?(How to position two elements side by side?)
  • 如何在vim中启用python3?(How to enable python3 in vim?)
  • 在MySQL和/或多列中使用多个表用于Rails应用程序(Using multiple tables in MySQL and/or multiple columns for a Rails application)
  • 如何隐藏谷歌地图上的登录按钮?(How to hide the Sign in button from Google maps?)
  • Mysql左连接旋转90°表(Mysql Left join rotate 90° table)
  • dedecms如何安装?
  • 在哪儿学计算机最好?
  • 学php哪个的书 最好,本人菜鸟
  • 触摸时不要突出显示表格视图行(Do not highlight table view row when touched)
  • 如何覆盖错误堆栈getter(How to override Error stack getter)
  • 带有ImageMagick和许多图像的GIF动画(GIF animation with ImageMagick and many images)
  • USSD INTERFACE - > java web应用程序通信(USSD INTERFACE -> java web app communication)
  • 电脑高中毕业学习去哪里培训
  • 正则表达式验证SMTP响应(Regex to validate SMTP Responses)