3

私は楽しみのために単純なチャットクライアントを作成しています。サーバー/クライアントが機能し、データを完全に送信しています。選択したユーザーにデータを送信する方法を知りたいです。選択部分は解決できますが、選択した IP に送信する方法がわかりません。これが私のサーバーです。

package Server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @class Connect
 * @date Feb 25, 2013 10:14:00 PM
 * @author Zach
 */

public class Connect { //Server
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(43595);

        while (server.isBound()) {

            Socket s = server.accept();
            DataOutputStream out = new DataOutputStream(s.getOutputStream());
            DataInputStream in = new DataInputStream(s.getInputStream());

            int length = in.read();
            byte[] data = new byte[length];
            in.read(data);
            String str = new String(data, "UTF-8");

            s.close();
        }
    }
}

サーバーから特定のクライアントに情報をリダイレクトしたい

4

2 に答える 2

1

あなたの場合は「s」ソケットから、受け入れられたソケットの配列を作成し、それをループして、データを送信するクライアントを見つけることができます。

于 2013-02-26T18:00:53.220 に答える
0

各クライアントを処理するクラスを作成します。

public class ClientHandler {

Socket connection;
DataInputStream in;
DataOutputStream out;

public ClientHandler(Socket s) {
    connection = s;
}
public void startup() throws IOException {
    in = new DataInputStream(connection.getInputStream());
    out = new DataOutputStream(connection.getOutputStream());
    out.flush();
}

public void sendMessage(byte[] message) throws IOException {
    out.write(message);
}

}

サーバーにリストを配置し、各ClientHandlerにIDを割り当てます。次に、リストをループして、IDが一致する場合は、クライアントでsendMessage()を使用します。

より効率的であるため、入力と出力にバッファーを使用することをお勧めします。また、特に複数のクライアントを処理する場合は、サーバークラスでスレッドを使用することをお勧めします。

于 2013-02-26T18:09:28.037 に答える