有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java ServerSocket在循环中不接收数据

我使用ServerSocket在一个while循环中从客户机获取数据,它在第一次运行时工作,但在第二次运行后失败

我做了一些搜索,但仍然不知道发生了什么

服务器端代码

package com.gorilla.main;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server2 {

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

        ServerSocket serverSocket = new ServerSocket(44444);

        while(true){

        System.out.println("another round");

        Socket socket  = serverSocket.accept();
        InputStream inputStream = socket.getInputStream();

        System.out.println("available: "+ inputStream.available());

        byte[] b = new byte[inputStream.available()];

        inputStream.read(b);

        System.out.println(new String(b));
        System.out.println("=======================");

        socket.close();
        }
    }
}

克莱恩密码

package com.gorilla.main;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client2 {

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

        Socket socket = new Socket("127.0.0.1", 44444);
        String s = "Hello World";
        byte [] b = s.getBytes();
        socket.getOutputStream().write(b);;
        socket.close();

    }
}

在我运行客户端3次后,服务器端控制台的输出

another round
available: 11
Hello World
=======================
another round
available: 0

=======================
another round
available: 0

=======================
another round

如有任何建议,将不胜感激。谢谢


共 (0) 个答案