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 波形合成电路的设计学习
  • ¥15 unity脚本挂不上
  • ¥15 数学建模数学建模需要
  • ¥20 Java Sound Api 调用Mixer.getLine偶现Line unsupported错误。
  • ¥15 使用cuda加速opencv运算但是报错AttributeError: module 'cv2.cuda' has no attribute 'getCudaEnabledDeviceCount'
  • ¥15 java输入输出异常
  • ¥15 三子连珠对弈小游戏制作
  • ¥15 C++扑克牌游戏的编程
  • ¥15 有人能看一下我宿舍管理系统的报修功能该怎么改啊?链表那里总是越界
  • ¥15 cs loadimage运行不了,easyx也下了,没有用