当前位置: 首页>>代码示例>>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;未经允许,请勿转载。