让ServerSocket监听客户端

时间:2017-06-13 14:22:57

标签: java sockets

我已经实现了Andorid App,它通过套接字(TCP)与服务器端进行通信。当我单击Android应用程序中的按钮时,应用程序和服务器端之间正在建立通信以及正在交换消息。 为了再次与服务器通信,我必须再次在Eclipse中运行服务器。我想运行服务器端一次,当clientSocket缓冲区中没有数据时,如果Android用户发送新请求,服务器应该再次监听  我试图通过使用Runnable类来管理它,但我还是要在Eclipse中再次运行服务器端?我怎样才能让它发挥作用?

public class Server{

    public static void main(String args[]) throws Exception {
        Cg2AapiServer.startServer();

    }

    private static void startServer() {

        Runnable serverTask = new Runnable() {

            @Override
            public void run() {
                try {

                    ServerSocket serverSocket = new ServerSocket(27015);
                    Socket clientSocket = serverSocket.accept();

                    Cg2AapiServer.bufferedInputStream = new BufferedInputStream(clientSocket.getInputStream());
                    Cg2AapiServer.outputStream = clientSocket.getOutputStream();
                    Cg2AapiServer.smartCard = new SmartCard();
                    Cg2AapiServer.handleConnection();

                    Cg2AapiServer.bufferedInputStream.close();
                    Cg2AapiServer.outputStream.close();
                    clientSocket.close();
                } catch (IOException e) {
                    System.err.println("Unable to process client request");
                    e.printStackTrace();
                }
            }
        };
        Thread serverThread = new Thread(serverTask);
        serverThread.start();

        System.out.println("At the end of the startServer method!");

    }


    private static void handleConnection() throws IOException {
        ByteBuffer receiveBuffer = ByteBuffer.allocate(Cg2AapiServer.RECEIVE_BUFFER_LENGTH);
        int readBytes = 0;
        while (true) {
            readBytes = Cg2AapiServer.bufferedInputStream.read(receiveBuffer.array(), receiveBuffer.position(),
                    receiveBuffer.remaining());
            System.out.println("readBytes: " + readBytes);
            if (readBytes < 0) {
                             // What should I do here when the readBytes = -1
                Cg2AapiServer.startServer(); //With this line I am getting the error below.
                break;
            }
       }

}

错误

  

无法处理客户端请求java.net.BindException:Address   已经在使用中:JVM_Bind at   java.net.DualStackPlainSocketImpl.bind0(Native Method)at   java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)     在   java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:376)     在java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)at   java.net.ServerSocket.bind(ServerSocket.java:376)at   java.net.ServerSocket。(ServerSocket.java:237)at   java.net.ServerSocket。(ServerSocket.java:128)at   Cg2AapiServer $ 1.run(Cg2AapiServer.java:42)at   java.lang.Thread.run(Thread.java:745)

0 个答案:

没有答案