ユーザーが「who」という単語を含むメッセージをサーバーに送信したときに、現在サーバー上にいるすべての人を知らせるパケットをユーザーに送り返そうとしています。
これが私のコードです:
else if( response.contains( "who" ) )
{
System.out.println( "Size of names collection: "+names.size() );
buf = null;
buf = names.toString().getBytes();
int thisPort = packet.getPort();
packet = new DatagramPacket( buf, buf.length,packet.getAddress(),thisPort );
socket.send(packet);
}
上記の print ステートメントの出力は 2 で、andrew と james のように 2 人が参加していることを示しています。パッケージ化して送信すると、次のように出力されると予想されます。
[アンドリュー、ジェームズ]
ただし、代わりにクライアントは次のようになります。
[アンドリュー、
以上です。どうしたの?ところで、これにはUDPを使用する必要があり、TCPに切り替えることはできません
アップデート
パケットを受信するクライアント クラスのコードは次のとおりです。
while( true )
{
try
{
// Set the buf to 256 to receive data back from same address and port
buf = null;
buf = new byte[256];
packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.receive(packet);
String response = new String( packet.getData() );
// Receive the packet back
System.out.println( response );
}
catch( IOException e )
{
}
}