dongxing2263 2017-04-21 12:41
浏览 96
已采纳

阅读后Java Server Socket关闭

I try and fail to create a bridge between PHP and Java. With my method, it works to send one string, but the server closes after reading the data.

This is my Class in Java:

public class Server {

private static BufferedReader inputstream;
private static BufferedWriter outputstream;
private static ServerSocket server;

public static void main(String[] args){
    System.out.println("Server gestartet");
    createServer();
}

private static void createServer() {
    try {
        server = new ServerSocket(6666);
        Socket client = server.accept();
        inputstream = new BufferedReader(new InputStreamReader(client.getInputStream()));
        outputstream = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));

        String temp = null;

        while((temp = inputstream.readLine()) != null){
            System.out.println(temp);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        inputstream.close();
        outputstream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
  }
 }

And this is how I send the String from PHP:

<?php 
 $socket = fsockopen('localhost', 6666, $errno, $errstr, 30);

 if(!$socket){
     echo("$errno <br> $errstr");
  }

 fwrite($socket, "Hello its me
");
 fclose($socket);
 ?>

Many thanks in advance, I hope you can help me :)

  • 写回答

1条回答 默认 最新

  • duanfeigui6655 2017-04-21 12:49
    关注

    You have to loop server.accept() in your java code.

    In your java code, you accept client connection once, read incoming data and that's all, your application ends.

    You can accept new connections in a loop, and process data in dedicated threads. Also consider using try with resources for your streams.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突