多线程服务器中的线程连接

时间:2013-11-23 05:02:11

标签: java multithreading sockets arraylist client

我正在实现一个带有多线程服务器的客户端服务器程序,该服务器有一个ArrayList,各种客户端将数据发送到ArrayList,并将它们添加到ArrayList中。

客户:

package p2pclient;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;

public class client {
    public static void main(String[] args) {
        Socket smtpSocket = null;  
        DataOutputStream os = null;
        DataInputStream is = null;
        Scanner s = new Scanner(System.in);

        try {
            smtpSocket = new Socket("localhost", 8888);
            os = new DataOutputStream(smtpSocket.getOutputStream());
            is = new DataInputStream(smtpSocket.getInputStream());
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: hostname");
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: hostname");
        }

        if (smtpSocket != null && os != null && is != null) {
            try {
                while(true)
                {
                    os.flush();
                    System.out.println("enter line");
                    String a = s.nextLine();
                    os.writeBytes(a + "\n");

                    System.out.println("wrote bytes");
                    String responseLine;

                    responseLine = is.readLine();
                    System.out.println("Server: " + responseLine);
                    if (responseLine.indexOf("Ok") != -1) {
                        System.out.println("breaking");
                        break;
                    }
                }
                os.close();
                is.close();
                smtpSocket.close();  
            } catch (UnknownHostException e) {
                System.err.println("Trying to connect to unknown host: " + e);
            } catch (IOException e) {
                System.err.println("IOException:  " + e);
            }
        }
        System.out.println("out of while");
    }           
}

服务器主题:

package server;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

public class ServerThread {

    public static void main(String args[]) throws InterruptedException {
        ServerSocket echoServer = null;
        Scanner s = new Scanner(System.in);
        String line;
        ArrayList<String> add_list = new ArrayList<String>();
        Collections.synchronizedList(add_list);
        int number=0;
        DataInputStream is;
        PrintStream os;
        Socket clientSocket = null;
        try {
            echoServer = new ServerSocket(8888);
        }
        catch (IOException e) {
            System.out.println(e);
        }   

        List<Thread> threads = new ArrayList<Thread>();
        while(true) {
            try {
                clientSocket = echoServer.accept();

                /* start a new thread to handle this client */
                number++;

                Thread t = new Thread(new ClientConn(clientSocket,number,add_list));
                t.start();
                threads.add(t);

            }catch (IOException e) {
                System.err.println("Accept failed.");
                System.err.println(e);
                System.exit(1);
            } 
            for (Thread t2 : threads)
            {
                t2.join();
            }
            System.out.println(add_list);
        }      
    }
}

服务器可运行的进程:

 package server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;

class ClientConn implements Runnable {

    Socket client;
    DataInputStream in;
    DataOutputStream out;
    int s;
    ArrayList<String> al = new ArrayList<String>();

    ClientConn(Socket client,int s, ArrayList<String> al){
        this.client = client;
        this.s = s;
        this.al = al;

        try {
            in = new DataInputStream(client.getInputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            out = new DataOutputStream(client.getOutputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @SuppressWarnings("deprecation")
    @Override
    public void run() {
        // TODO Auto-generated method stub
        String response = "";

        try { 
            while (true) {
            response = "";
            response = in.readLine();
            out.writeBytes(response+"\n");
            if (response.indexOf("Ok") == -1)
                al.add(response);
            //  System.out.println(response);
            out.flush();
            if (response.indexOf("Ok") != -1) {
                //System.out.println("breaking");
                break;
            }
        }   
        } catch (IOException e) {
            System.err.println(e);
        }
    }
}

我试图将所有线程放在ArrayList中并加入主线程上的每个线程。这不起作用。相反,每个线程都在第一个线程上等待。

如何在打印数组列表之前让主线程等待其他线程结束?

1 个答案:

答案 0 :(得分:0)

尝试将while主题中的Server循环更改为:

while(true) {
    try {
        clientSocket = echoServer.accept();
        number++;
        Thread t = new Thread(new ClientConn(clientSocket,number,add_list));
        t.start();
        t.join();
        threads.add(t);
    } catch (IOException e) {
            System.err.println("Accept failed.");
            System.err.println(e);
            System.exit(1);
    } 
    System.out.println(add_list);
}