ServerSocket
は、クライアントが認識しているポートでリッスンするポートを1つだけ持つ必要があります。クライアントがサーバーに接続すると、新しいSocket
オブジェクトが作成され、元のServerSocket
は再びリスニングに戻ります。新しいThread
をスピンオフするか、Executor
に実際に話す作業を渡す必要があります。そうしないと、サーバーはクライアント接続の受信を停止します。
ここには非常にのコードの基本的なスケッチがあります。
import java.net.*;
import java.util.concurrent.*;
public class CoordinateServer {
public static void main(String... argv) throws Exception {
// 'port' is known to the server and the client
int port = Integer.valueOf(argv[0]);
ServerSocket ss = new ServerSocket(port);
// You should decide what the best type of service is here
ExecutorService es = Executors.newCachedThreadPool();
// How will you decide to shut the server down?
while (true) {
// Blocks until a client connects, returns the new socket
// to use to talk to the client
Socket s = ss.accept();
// CoordinateOutputter is a class that implements Runnable
// and sends co-ordinates to a given socket; it's also
// responsible for cleaning up the socket and any other
// resources when the client leaves
es.submit(new CoordinateOutputter(s));
}
}
}
彼らが始めるのは簡単ですので、私はここにソケットを入れているが、あなたはこのうまく機能しており、あなたのパフォーマンスを向上したいたら、あなたはおそらくjava.nio.channels
パッケージを調査したいと思うでしょう。良いチュートリアルover at IBMがあります。
出典
2013-06-20 08:31:42
rxg
はいです。 1つのServerSocketですが、クライアントを処理する複数のソケットとスレッド。 – Thihara
無限のスレッド作成に注意してください!スレッドの合計数を制限するほうがよいでしょう。最善の策はここで 'ExecutorService'を使うことです。 – fge
接続を処理するソケットを作成して、ユーザーを一意のソケットに誘導するだけでいいですか? – user2016705