-1

如何在 Java 中实现多线程服务器?服务器侦听端口(例如 5000)并在单独的线程中提供连接并继续侦听更多客户端。

4

1 回答 1

3

这是一个典型的例子:

ServerSocket ss = new ServerSocket(port);
ExecutorService executor = Executors.newCachedThreadPool();

while(true)
{
    Socket s = ss.accept();
    Runnable r = new TaskImplementsRunnable(s);
    executor.submit(r)
}
public class TaskImplementsRunnable implements Runnable
{
    private Socket socket;

    public TaskImplementsRunnable(Socket socket)
    {
        this.socket = socket;
    }

    @Override
    public void run()
    {
        try
        {
            PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader reader = new BufferedReader(new  InputStreamReader(socket.getInputStream()));

            String command;
            while((command = reader.readLine()) != null)
            {
                if(command.equalsIgnoreCase("command 1"))
                {
                    writer.println("This is command 1!");
                }
                else if(command.equalsIgnoreCase("command 2"))
                {
                    writer.println("This is command 2!");
                }
                else if(command.equalsIgnoreCase("exit"))
                {
                    break;
                }
                else
                {
                    writer.println("This is unknown command!");
                }
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }

        try
        {
            writer.close();
            reader.close();
        }
        catch(IOException e){}
    }
}
于 2013-03-11T23:47:51.567 回答