我怎么能有一个多个客户端可以读写的链表?

时间:2015-03-14 19:02:32

标签: java multithreading client server

我有一个多线程服务器,可以同时连接多个客户端。这些线程调用具有多个链接列表的类,客户端可以向其添加和删除信息。 例如 这是服务器

public class ShareServer {
    public static void main(String[] args) throws IOException {

    //if (args.length != 1) {
        //System.err.println("Usage: java ShareServer <port number>");
        //System.exit(1);
    //}

       //int portNumber = 2000;
        boolean listening = true;

        try (ServerSocket serverSocket = new ServerSocket(2000)) { 
            while (listening) {
                new ClientThread(serverSocket.accept()).start();
            }
        } catch (IOException e) {
            System.err.println("Could not listen on port " + 2000);
            System.exit(-1);
        }
    }
}

这是clientsthread

public class ClientThread extends Thread {
private Socket socket = null;
private ObjectOutputStream out;
private ObjectInputStream in;
FindMatch look= new FindMatch();
string fruit;

public ClientThread(Socket socket) {
    super("ClientThread");
    this.socket = socket;
}

public void run() {

    try {
        out = new ObjectOutputStream (socket.getOutputStream());
        in = new ObjectInputStream (socket.getInputStream());

        int count=0;
            boolean flag = false;

                try{

                    fruit = (Double)in.readObject();

                        flag = look.checkForMatch(string fruit);
                        if(flag==true)
                            sendMessage("found a match")


                }


                catch(ClassNotFoundException classnot){
                    System.err.println("Data received in unknown format");
                }

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

}

void sendMessage(string fuit)
{
    try{
        out.writeObject(msg);
        out.flush();
        System.out.println("server>" + msg);
    }
    catch(IOException ioException){
        ioException.printStackTrace();
    }
}
}



   public LinkedList<String> fruitEntries = new LinkedList<Integer>();
public LinkedList<?> clientID = new LinkedList <?>();

这是它调用的代码

boolean checkFormatch(string fruit){   
for(int i = 0; i< fruitEntries.length();i++){
        if(fruit == fruitEntries.get(i)){
            tell client at clientID(i);
            fruitEntries.remove(i);
            clientID.remove(i);
            retutn true;
        }
}
}

这段代码远非完美我只是把它放在一起。一般的想法是正确的。我可能会有6个链接的信息列表。 我不确定如何跟踪客户端的线程,所以我很感激你的帮助。

1 个答案:

答案 0 :(得分:0)

我个人会使用RMI而不是套接字。 RMI处理所有混乱的监听线程等。

考虑使用java.util.concurrent类之一 - ConcurrentSkipListMap 的ConcurrentHashMap

另外,当你比较字符串时,你需要fruit.compareTo(...)这是相当慢的,所以创建一个哈希可能更好。