处理单个客户端的多个客户端Java Socket instad

时间:2017-05-24 19:02:21

标签: java android sockets

我正在与Java Server Socket和Android客户端进行一些聊天。 我完成了接受单个客户端连接,但问题是当我尝试做多个客户端时。

我对此非常陌生,我正在寻找可以帮助我编写代码的人,谢谢:

服务器:

public class SimpleChatServer {

public static void main(String[] args) {

    ServerSocket serverSocket = null;
    Socket clientSocket = null;
    boolean listening = true;
    try {
        serverSocket = new ServerSocket(6667);
        System.out.println("El servidor se ha iniciado. Escuchando el puerto 6667. Esperando al cliente.");
        while (listening){
            clientSocket = serverSocket.accept();
            System.out.println("Cliente conectado en el puerto 6667.");
            ChatWindow chatWindow = new ChatWindow();
            chatWindow.open(clientSocket);
        }

    } catch (IOException e) {
        System.out.println("Imposible escuchar el puerto 6667");
        e.printStackTrace();
        return;
    }

    ChatWindow chatWindow = new ChatWindow();
    chatWindow.open(clientSocket);
}

ChatWindow类:

public class ChatWindow extends JFrame {

private JTextArea chatView;
private JButton sendButton;
private JTextArea chatBox;

/**
 * This method open the chat window.
 * 
 * @param clientSocket
 *            Socket which has been opened for chat
 */
public void open(final Socket clientSocket) {

    initComponents();

    setWinodwCloseListnerToCloseSocket(clientSocket);

    initSenderAndReceiver(clientSocket);

}

/**
 * This method initialize the components of the chat winodow.
 */
private void initComponents() {

    chatView = new JTextArea(20, 46);
    JScrollPane chatViewScrollPane = new JScrollPane(chatView);
    chatBox = new JTextArea(5, 40);
    JScrollPane chatBoxScrollPane = new JScrollPane(chatBox);
    sendButton = new JButton("Send");

    setResizable(false);
    setTitle("Chat Server");
    setSize(550, 450);
    Container contentPane = getContentPane();
    contentPane.setLayout(new FlowLayout());
    contentPane.add(chatViewScrollPane);
    contentPane.add(chatBoxScrollPane);
    contentPane.add(sendButton);
    chatView.setEditable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
}

/**
 * This method initialize the chat sender and receiver for this chat window.
 * 
 * @param clientSocket
 *            Socket which has been opened for chat
 */
private void initSenderAndReceiver(final Socket clientSocket) {

    Receiver receiver = new Receiver(clientSocket, chatView);
    final Sender sender = new Sender(clientSocket, chatView);

    sendButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            sender.sendMessage(chatBox.getText());
            chatBox.setText(""); //Clear the chat box
        }
    });

    Thread receiverThread = new Thread(receiver);
    receiverThread.run();
}

/**
 * This method register window closing listener to close the clientSocket
 * when the chat window is closed.
 * 
 * @param clientSocket
 *            Socket which has been opened for chat
 */
private void setWinodwCloseListnerToCloseSocket(final Socket clientSocket) {
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            try {
                clientSocket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    });
}

发件人和收件人:

public class Sender {

private PrintWriter out;
private JTextArea chatView;


public Sender(Socket clientSocket, JTextArea chatViewParam) {
    chatView = chatViewParam;

    try {
        out = new PrintWriter(clientSocket.getOutputStream(), true);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void sendMessage(String message) {
    out.println(message); // Print the message on output stream.
    chatView.append("Server: " + message + "\n"); // Print the message on chat window.
}



public class Receiver implements Runnable {

private BufferedReader bufferedReader;
private JTextArea chatView;


public Receiver(Socket clientSocket, JTextArea chatViewParam) {
    chatView = chatViewParam;

    try {
        InputStreamReader inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
        bufferedReader = new BufferedReader(inputStreamReader);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

@Override
public void run() {

    String message;

    while (true) {
        try {
            if (bufferedReader.ready()) {
                message = bufferedReader.readLine(); // Read the chat message.
                chatView.append("Client: " + message + "\n"); // Print the chat message on chat window.
            }
        } catch (IOException ex) {
            System.out.println("Problem in message reading");
            ex.printStackTrace();
        }

        try {
            Thread.sleep(500);
        } catch (InterruptedException ie) {
        }
    }

}

最后,客户活动:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.channel_movies_activity_2);
    textField = (EditText) findViewById(R.id.editText1);
    button = (Button) findViewById(R.id.button1);
    textView = (TextView) findViewById(R.id.textView1);

    ChatOperator chatOperator = new ChatOperator();
    chatOperator.execute();

}

/**
 * This AsyncTask create the connection with the server and initialize the
 * chat senders and receivers.
 */
private class ChatOperator extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... arg0) {
        try {
            client = new Socket(CHAT_SERVER_IP, 6667); // Creating the server socket.

            if (client != null) {
                printwriter = new PrintWriter(client.getOutputStream(), true);
                InputStreamReader inputStreamReader = new InputStreamReader(client.getInputStream());
                bufferedReader = new BufferedReader(inputStreamReader);
            } else {
                System.out.println("Server has not bean started on port 4444.");
            }
        } catch (UnknownHostException e) {
            System.out.println("Faild to connect server " + CHAT_SERVER_IP);
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Faild to connect server " + CHAT_SERVER_IP);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Following method is executed at the end of doInBackground method.
     */
    @Override
    protected void onPostExecute(Void result) {
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                final Sender messageSender = new Sender(); // Initialize chat sender AsyncTask.
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    messageSender.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                } else {
                    messageSender.execute();
                }
            }
        });

        Receiver receiver = new Receiver(); // Initialize chat receiver AsyncTask.
        receiver.execute();

    }

}

/**
 * This AsyncTask continuously reads the input buffer and show the chat
 * message if a message is availble.
 */
private class Receiver extends AsyncTask<Void, Void, Void> {

    private String message;

    @Override
    protected Void doInBackground(Void... params) {
        while (true) {
            try {

                if (bufferedReader.ready()) {
                    message = bufferedReader.readLine();
                    publishProgress(null);
                }
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                Thread.sleep(500);
            } catch (InterruptedException ie) {
            }
        }
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        textView.append("Server: " + message + "\n");
    }

}

/**
 * This AsyncTask sends the chat message through the output stream.
 */
private class Sender extends AsyncTask<Void, Void, Void> {

    private String message;

    @Override
    protected Void doInBackground(Void... params) {
        message = textField.getText().toString();
        printwriter.write(message + "\n");
        printwriter.flush();

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        textField.setText(""); // Clear the chat box
        textView.append("Client: " + message + "\n");
    }
}

我想处理多个发送client_id的客户端,并向所有客户端发送消息,并通过分开的方式向特定客户端发送消息。

感谢所有人!

0 个答案:

没有答案