线程服务器/客户端在第二个客户端加入后停止

时间:2014-03-29 10:55:18

标签: java multithreading networking client

我有一台服务器,它使用多个线程来接受多个客户端。我现在有这样的情况,当客户端输入内容时,它会在服务器上显示为Client:text这适用于1个客户端。但问题是当第二个客户端加入时。

他们加入很好,他们可以打字。但是第一个客户端只能输入1个然后停止的东西,即他们的消息不会出现在服务器上。我认为他们可以做1,因为方法已经开始但不重复。我尝试了一段时间(真实)循环(如代码所示)并在最后调用该方法,但都没有工作。我是编程新手,所以不具备这方面的专业知识。请找到下面的代码:)(注意,缩进是正确的,只是没有正确复制)

服务器:

    package dod;

    import java.net.*;
    import java.util.*;
    import java.util.concurrent.atomic.AtomicInteger;
    import java.io.*;

    public class Server implements Runnable
    {
    PrintWriter out;
    BufferedReader in;
    Socket clientSocket;
    ServerSocket serverSocket;
    int portNumber;
    AtomicInteger numClients = new AtomicInteger(0);


    public static void main(String[] args)
    {
        Server s = new Server();

        s.startup();
    }

    public void run()
    {}


    /**
     * Start the server on the user picked port
     */
    public void startup()
    {   
        try 
        {
            System.out.println("Enter a port");
            Scanner dif = new Scanner(System.in);
            portNumber = Integer.parseInt(dif.nextLine());
            dif.close();

            serverSocket = new ServerSocket(portNumber);
            newThread();
        }
        catch (IOException e) {
            System.out.println("Error");
            System.exit(0);
        }
    }


    public void newThread()
    {
        Thread thread =new Thread("C"+numClients.getAndIncrement())
        {
            public void run()
            {
                accept();
            }
        };
        thread.start();
    }

    public void accept()
    {
        try
        {
            clientSocket = serverSocket.accept();
            System.out.println("A new client has just connected.");
        } catch(IOException e)
        {
            System.out.println("error");
            System.exit(0);
        }
        newThread();
        listenCommand();

    }


    public void listenCommand()
    {
        while (true)
        {
            try
            {
                out = new PrintWriter(clientSocket.getOutputStream(), true);                   
                in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

                String userInput;
                while ((userInput = in.readLine()) != null)
                {
                    System.out.println("client: " + userInput);
                }
            } catch (IOException e)
            {
                System.out.println("Error");
                System.exit(0);
            }
        }
    }
}

客户:

    package dod;

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


    public class Client
    {
    public static void main(String[] args) throws IOException {
        String hostName = args[0];
        int portNumber = Integer.parseInt(args[1]);

        try {
            Socket serverSocket = new Socket(hostName, portNumber);
            PrintWriter out = new PrintWriter(serverSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

            String userInput;
            while ((userInput = stdIn.readLine()) != null)
            {
                out.println(userInput);
            }
        } catch(UnknownHostException e) {
            System.out.println("error in host");
        } catch(IOException e) {
            System.out.println("error in IO");
        }


    }
}

谢谢! :)

1 个答案:

答案 0 :(得分:1)

*强调文本*在Server类中,您应该有一个Thread侦听新客户端到达并为它们分配自己的套接字。您将套接字和流作为成员变量,因此每次新客户端都会替换套接字。您也可以为接受连接打开一个新线程,而不是为客户端本身打开。

检查以下内容(看到客户端套接字是另一个线程,我为它创建了一个Runnable):

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;

public class Server
{
    ServerSocket serverSocket;
    int portNumber;
    AtomicInteger numClients = new AtomicInteger(0);


    public static void main(String[] args)
    {
        Server s = new Server();

        s.startup();
    }


    /**
     * Start the server on the user picked port
     */
    public void startup()
    {   
        try 
        {
            System.out.println("Enter a port");
            Scanner dif = new Scanner(System.in);
            portNumber = Integer.parseInt(dif.nextLine());
            dif.close();

            serverSocket = new ServerSocket(portNumber);
            newThread();
        }
        catch (IOException e) {
            System.out.println("Error");
            System.exit(0);
        }
    }


    public void newThread()
    {
        Thread thread =new Thread("C"+numClients.getAndIncrement())
        {
            public void run()
            {   
                while(true) {
                    try {
                        accept();
                    } catch (Exception e) {
                        // lof the exception
                    }
                }
            }
        };
        thread.start();
    }

    public void accept()
    {
        try
        {
            Socket clientSocket = serverSocket.accept();
            new Thread(new ClientSocket(clientSocket)).start();
            System.out.println("A new client has just connected.");
        } catch(IOException e)
        {
            System.out.println("User disconnected");
            System.exit(0);
        }
    }


    class ClientSocket implements Runnable {
        Socket clientSocket;

        public ClientSocket(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        public void run() {
            {
                try
                {
                    PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);                   
                    BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

                    String userInput;
                    while ((userInput = in.readLine()) != null)
                    {
                        System.out.println("client: " + userInput);
                    }
                } catch (IOException e)
                {
                    System.out.println("Error. Probably client disconnected");
                    // System.exit(0); do you want to exist when a client disconnects?
                }
            }
        }
    }
}