Java客户端 - 服务器递增和递减客户端计数

时间:2016-03-21 23:55:51

标签: java multithreading server client

我正在尝试自学Java编程。目前我正在研究一些客户端 - 服务器代码。我的目标是在线程启动之前增加客户端计数,并在线程完成时减少计数。现在,线程只是睡了几秒钟。你可以在这里看到完整的指示:

http://archive.oreilly.com/oreillyschool/courses/java5/Homework/Projects/serverEssentials_proj.project.html

以下是我目前的代码:

RepositoryServer.java

package server;

import java.io.*;
import java.net.*;

public class RepositoryServer {
    ServerSocket serverSocket = null;
    int state = 0;

    public void bind() throws IOException {
        serverSocket = new ServerSocket(9172);
        state=1;
    }

    public void process() throws IOException {
        while (state ==1) {
            Socket client = serverSocket.accept();

            new RepositoryThread(client).start();
        }

        shutdown();
    }

    void shutdown() throws IOException {
        if (serverSocket != null) {
            serverSocket.close();
            serverSocket=null;
            state=0;
        }
    }
}

RepositoryClient.java

package client;

import java.io.*;
import java.net.*;

public class RepositoryClient {
    public static void main(String[] args) throws Exception {
        Socket server = new Socket("localhost", 9172);

        PrintWriter toServer = new PrintWriter (server.getOutputStream(),true);
        BufferedReader fromServer = new BufferedReader (new InputStreamReader(server.getInputStream()));

        for (int num=0; num<3; num++) {
            toServer.println("SIZE");
            if (!toServer.checkError()) {
                int response = Integer.valueOf(fromServer.readLine());
                String value = fromServer.readLine();
                if (response==0) {
                    System.out.println(num + ": Number of Images: "+ value);
                } else if (response==-1) {
                    System.err.println(value);
                } else {
                    System.err.println("Received unknown response: " +response);
                }
            }
        }

        server.close();
    }
}

RepositoryThread.java

package server;

import java.io.*;
import java.net.*;

public class RepositoryThread extends Thread {
    Socket client;
    BufferedReader fromClient;
    PrintWriter toClient;

    RepositoryThread (Socket s) throws IOException {
        fromClient = new BufferedReader(new InputStreamReader(s.getInputStream()));
        toClient=new PrintWriter(s.getOutputStream(), true);
        client = s;
    }

    public void run() {
        try {
            while (true) {
                String request = fromClient.readLine();
                if (request == null) {
                    break;
                }

                if (request.equals("SIZE")) {
                    output("0");
                } else {
                    //internal server error. Try to continue and keep processing
                    outputError("Unable to process request: "+ request);
                    continue;
                }
            }
        } catch (IOException ioe) {
            System.err.println("Thread processing terminated: " + ioe.getMessage());
        }

        try {
            fromClient.close();
            toClient.close();
            client.close();
        } catch (IOException ioe) {
            System.err.println("Unable to close connection: " +ioe.getMessage());
        }
    }

    void output(String result) {
        toClient.println(0);
        toClient.println(result);
    }

    void outputError(String error) {
        toClient.println(-1);
        toClient.println(error);
    }
}

ServerLauncher.java

package server;

public class ServerLauncher {
    public static RepositoryServer create() throws Exception {
        RepositoryServer server = new RepositoryServer();
        server.bind();
        return server;
    }

    public static void main(String[] args) throws Exception {
        RepositoryServer server = create();

        System.out.println("Server awaiting client connections");
        server.process();
        System.out.println("Server shutting down.");
    }
}

TestServer.java

package server;

import java.io.*;
import client.*;
import junit.framework.TestCase;

public class TestServer extends TestCase {
    static int clientCount =0;
    public void testMultipleClients() throws Exception {
        RepositoryServer server = launchServer();

        System.out.println(clientCount);
        launchClient();
        System.out.println(clientCount);
        launchClient();
        System.out.println(clientCount);
        launchClient();
        System.out.println(clientCount);

        //wait until everything done.
        //isClientCountZero();
        Thread.sleep(10000);

        server.shutdown();
        assertEquals(0, server.state);
    }

    public static void launchClient() {
        //incrementClientCount();
        new Thread() {

            public void run() {
                try {

                    RepositoryClient.main(new String[]{});

                } catch (Exception e) {
                    System.err.println("Unable to launch test client.");
                }
            }
        }.start();
        //decrementClientCount();
    }

    public static RepositoryServer launchServer() throws Exception {
        final RepositoryServer server = ServerLauncher.create();
        assertEquals(1, server.state);

        new Thread() {
            public void run() {
                try {
                    server.process();
                } catch (IOException ioe) {
                    System.err.println("Server completed");
                }
            }
        }.start();

        Thread.sleep(2000);

        return server;
    }

    public static synchronized boolean isClientCountZero(){
        if (clientCount==0) {
            return true;
        } else {
            return false;
        }
    }

    public static synchronized void decrementClientCount(){
        clientCount--;
    }

    public static synchronized void incrementClientCount(){
        clientCount++;
    }
}

有问题的代码在TestServer.java中。当Thread.sleep()方法处于活动状态时,服务器会按预期输出文本。但是,当Thread.sleep()方法被注释掉并用increment,decrement和clientCount方法替换时,它不再输出任何文本,只是服务器已完成&#39;。我对发布链接的解决方案有什么问题?

谢谢

0 个答案:

没有答案