當前位置: 首頁>>代碼示例>>Java>>正文


Java ServerSocket類代碼示例

本文整理匯總了Java中java.net.ServerSocket的典型用法代碼示例。如果您正苦於以下問題:Java ServerSocket類的具體用法?Java ServerSocket怎麽用?Java ServerSocket使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ServerSocket類屬於java.net包,在下文中一共展示了ServerSocket類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: printSockets

import java.net.ServerSocket; //導入依賴的package包/類
@Test
public void printSockets() throws IOException {
	
	ServerSocket ss = new ServerSocket();
	ss.bind(sock(5000));
	
	Socket s1 = new Socket();
	Socket s2 = new Socket();
	
	s1.connect(sock(5000));
	s2.connect(sock(5000));
	
	ss.close();
	s1.close();
	// s2 remains unclosed
	
	HeapImage hi = HeapUnit.captureHeap();
	
	for(HeapInstance i: hi.instances(SocketImpl.class)) {
		// fd field in SocketImpl class is nullified when socket gets closed
		boolean open = i.value("fd") != null;
		System.out.println(i.rehydrate() + (open ? " - open" : " - closed"));
	}
}
 
開發者ID:aragozin,項目名稱:heapunit,代碼行數:25,代碼來源:DumpSocketsExample.java

示例2: main

import java.net.ServerSocket; //導入依賴的package包/類
public static void main(String argv[]) throws Exception {
    AutoRunFromConsole.runYourselfInConsole(true);
    String clientSentence;
    ServerSocket welcomeSocket = new ServerSocket(4405);
    System.out.println("Logger started!");
    PrintWriter outPrinter = new PrintWriter("tcp_log.txt");
    while (true) {
      
        Socket connectionSocket = welcomeSocket.accept();
        BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
        while (true) {
            try {
                clientSentence = inFromClient.readLine();
                if (clientSentence == null) break;
                System.out.println(clientSentence);
                outPrinter.println(clientSentence);
                outPrinter.flush();
            } catch (Exception e) {
                break;
            }                
        }
        
        System.out.println("Connection closed.");
    }
}
 
開發者ID:Maschell,項目名稱:nn_nex_logging_and_research,代碼行數:26,代碼來源:TCPServer.java

示例3: TLSServer

import java.net.ServerSocket; //導入依賴的package包/類
/**
 * Creates a new Server using TLS
 */
public TLSServer(final byte[] keyStore, final char[] keyStorePassword, final String keyStoreType) throws IOException
{
    super(new ServerImpl(
            new ServerSocketFactory()
            {
                @Override
                public ServerSocket getServerSocket(final int port) throws Exception
                {
                    return new TLSBuilder()
                            .withPort(port)
                            .withKeyStore(keyStoreType, new ByteArrayInputStream(keyStore), keyStorePassword)
                            .buildServerSocket();
                }
            },
            new ClientFactory()
            {
                @Override
                public Client getClient()
                {
                    return new TLSClient();
                }
            }
    ));
}
 
開發者ID:PvdBerg1998,項目名稱:PNet,代碼行數:28,代碼來源:TLSServer.java

示例4: testCloseServerSocketThrowsIOException

import java.net.ServerSocket; //導入依賴的package包/類
@Test
public void testCloseServerSocketThrowsIOException() throws IOException {
  final ServerSocket mockServerSocket =
      mockContext.mock(ServerSocket.class, "closeServerSocketThrowsIOExceptionTest");

  mockContext.checking(new Expectations() {
    {
      oneOf(mockServerSocket).close();
      will(throwException(new IOException("test")));
    }
  });

  try {
    assertFalse(SocketUtils.close(mockServerSocket));
  } catch (Throwable t) {
    fail("Calling close on a ServerSocket using SocketUtils threw an unexpected Throwable (" + t
        + ")!");
  }
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:20,代碼來源:SocketUtilsJUnitTest.java

示例5: start

import java.net.ServerSocket; //導入依賴的package包/類
/**
 * Starts the server
 * @return Server This Server
 */
public final Server start() {
    try {
        boolean port_valid = checkPortAvailable(port);
        if(port_valid) {
            stopThread(thread_receive);
            serversocket = new ServerSocket(port);
            instant_started = Instant.now();
            started = true;
            registerServerPort(port);
            StaticStandard.log("[SERVER] Started server on port: " + port);
            resetThreadReceive();
            startThread(thread_receive);
            timer.start();
        } else {
            instant_started = null;
            StaticStandard.logErr("[SERVER] Failed starting server on port: " + port + ", port already binded");
        }
    } catch (Exception ex) {
        instant_started = null;
        StaticStandard.logErr("[SERVER] Error while starting server: " + ex, ex);
    }
    return this;
}
 
開發者ID:Panzer1119,項目名稱:JAddOn,代碼行數:28,代碼來源:Server.java

示例6: setUp

import java.net.ServerSocket; //導入依賴的package包/類
@Before
public void setUp(TestContext context) throws IOException {
    vertx = Vertx.vertx();

    // Pick an available and random
    ServerSocket socket = new ServerSocket(0);
    port = socket.getLocalPort();
    socket.close();

    DeploymentOptions options = new DeploymentOptions()
        .setConfig(new JsonObject()
            .put("HTTP_PORT", port)
            .put("url", "jdbc:hsqldb:mem:test?shutdown=true")
            .put("driver_class", "org.hsqldb.jdbcDriver")
        );
    vertx.deployVerticle(MyFirstVerticle.class.getName(), options, context.asyncAssertSuccess());
}
 
開發者ID:cescoffier,項目名稱:introduction-to-vert.x,代碼行數:18,代碼來源:MyFirstVerticleTest.java

示例7: createServerSocket

import java.net.ServerSocket; //導入依賴的package包/類
public ServerSocket createServerSocket(int port) throws IOException {
  ServerSocket sock = null;
  if ("".equals(bindAddress)) {
    sock = socketCreator.createServerSocket(port, this.backlog);
  } else {
    sock = socketCreator.createServerSocket(port, this.backlog,
        InetAddressUtil.toInetAddress(this.bindAddress));
  }

  if (logger.isDebugEnabled()) {
    logger.debug(
        "MX4JServerSocketFactory RMIServerSocketFactory, INetAddress {}, LocalPort {}, LocalSocketAddress {}",
        sock.getInetAddress(), sock.getLocalPort(), sock.getLocalSocketAddress());
  }
  return sock;
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:17,代碼來源:MX4JServerSocketFactory.java

示例8: run

import java.net.ServerSocket; //導入依賴的package包/類
@Override
public void run() {
    try {
        server.setServerSocket(new ServerSocket(server.getPort()));
        if (server.getTimeout() > 0) {
            server.getServerSocket().setSoTimeout(server.getTimeout());
        }
        server.setServerRunning(true);
        server.onServerStarted();

        while (server.isServerRunning()) {

            Socket socket = server.getServerSocket().accept();
            ListenToClient client = new ListenToClient(this, socket);
            client.setClientId(server.getNextUniqeID());
            server.getClients().add(client);
            client.startListener();

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    stopServer();
    server.onServerStopped();
}
 
開發者ID:bekiratas16,項目名稱:JavaLibraries,代碼行數:27,代碼來源:ServerRunner.java

示例9: startHttpServer

import java.net.ServerSocket; //導入依賴的package包/類
public void startHttpServer() {
    if (isServerAlive()) {
        return;
    }

    for (int port : new int[]{61593, 41123, 43387, 39083, 24423, 16834, 9289, 8452, 6217, 5300, 4118, 3787, 2998, 0}) {
        try {
            ServerSocket localServer = new ServerSocket(port);
            int localPort = localServer.getLocalPort();
            if (localPort <= 0) {
                continue;
            }
            mMainThread = new MainThread(localServer);
            mMainThread.start();
            break;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
開發者ID:ljian,項目名稱:PleaseWakeUp,代碼行數:21,代碼來源:SimpleHttpServer.java

示例10: Acceptor

import java.net.ServerSocket; //導入依賴的package包/類
public Acceptor(ServerSocket serverSocket, URI uri) {
    socket = serverSocket;
    target = uri;
    pause.set(new CountDownLatch(0));
    try {
        socket.setSoTimeout(ACCEPT_TIMEOUT_MILLIS);
    } catch (SocketException e) {
        e.printStackTrace();
    }
}
 
開發者ID:messaginghub,項目名稱:pooled-jms,代碼行數:11,代碼來源:SocketProxy.java

示例11: bind

import java.net.ServerSocket; //導入依賴的package包/類
protected void bind() throws IOException {
    // allocate an unbound server socket channel
    serverChannel = ServerSocketChannel.open();
    // Get the associated ServerSocket to bind it with
    ServerSocket serverSocket = serverChannel.socket();
    // create a new Selector for use below
    synchronized (Selector.class) {
        // Selector.open() isn't thread safe
        // http://bugs.sun.com/view_bug.do?bug_id=6427854
        // Affects 1.6.0_29, fixed in 1.7.0_01
        this.selector.set(Selector.open());
    }
    // set the port the server channel will listen to
    //serverSocket.bind(new InetSocketAddress(getBind(), getTcpListenPort()));
    bind(serverSocket,getPort(),getAutoBind());
    // set non-blocking mode for the listening socket
    serverChannel.configureBlocking(false);
    // register the ServerSocketChannel with the Selector
    serverChannel.register(this.selector.get(), SelectionKey.OP_ACCEPT);

    //set up the datagram channel
    if (this.getUdpPort()>0) {
        datagramChannel = DatagramChannel.open();
        configureDatagraChannel();
        //bind to the address to avoid security checks
        bindUdp(datagramChannel.socket(),getUdpPort(),getAutoBind());
    }
}
 
開發者ID:sunmingshuai,項目名稱:apache-tomcat-7.0.73-with-comment,代碼行數:29,代碼來源:NioReceiver.java

示例12: MockServerThread

import java.net.ServerSocket; //導入依賴的package包/類
public MockServerThread(ServerSocket serverSocket, Deque<ImapInteraction> interactions,
        CountDownLatch waitForConnectionClosed, CountDownLatch waitForAllExpectedCommands, Logger logger,
        KeyStoreProvider keyStoreProvider) {
    super("MockImapServer");
    this.serverSocket = serverSocket;
    this.interactions = interactions;
    this.waitForConnectionClosed = waitForConnectionClosed;
    this.waitForAllExpectedCommands = waitForAllExpectedCommands;
    this.logger = logger;
    this.keyStoreProvider = keyStoreProvider;
}
 
開發者ID:philipwhiuk,項目名稱:q-mail,代碼行數:12,代碼來源:MockImapServer.java

示例13: closeAllSockets_do

import java.net.ServerSocket; //導入依賴的package包/類
/**
 * Closes all of the opened sockets
 */
protected void closeAllSockets_do(boolean logWarning)
{
    int i = 0;

    for (DatagramSocket datagramsocket : this.socketList)
    {
        if (this.closeSocket(datagramsocket, false))
        {
            ++i;
        }
    }

    this.socketList.clear();

    for (ServerSocket serversocket : this.serverSocketList)
    {
        if (this.closeServerSocket_do(serversocket, false))
        {
            ++i;
        }
    }

    this.serverSocketList.clear();

    if (logWarning && 0 < i)
    {
        this.logWarning("Force closed " + i + " sockets");
    }
}
 
開發者ID:F1r3w477,項目名稱:CustomWorldGen,代碼行數:33,代碼來源:RConThreadBase.java

示例14: main

import java.net.ServerSocket; //導入依賴的package包/類
public static void main(String[] args) throws Exception {

        try (ServerSocket ss = new ServerSocket(0)) {
            runTest(OutputStreamGetter.class, ss);
            runTest(InputStreamGetter.class, ss);
        }

        if (failed)
            throw new RuntimeException("Failed, check output");
    }
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:11,代碼來源:Streams.java

示例15: ServerThread

import java.net.ServerSocket; //導入依賴的package包/類
public ServerThread(int port, ServerListener s){
	try {
		this.listener = s;
		server = new ServerSocket(port);
		this.port = port;
		this.start();
	} catch (IOException e) {
		if(e instanceof BindException){
			StatusPrinter.print("ERROR", "Server already running? [port:"+port+"]", ServerThread.class);
			if(listener!=null){listener.onBindException();}
		}else{
			e.printStackTrace();
		}
	}
}
 
開發者ID:ZetzmannM,項目名稱:CGL,代碼行數:16,代碼來源:ServerThread.java


注:本文中的java.net.ServerSocket類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。