本文整理汇总了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"));
}
}
示例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.");
}
}
示例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();
}
}
));
}
示例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
+ ")!");
}
}
示例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;
}
示例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());
}
示例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;
}
示例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();
}
示例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();
}
}
}
示例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();
}
}
示例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());
}
}
示例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;
}
示例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");
}
}
示例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");
}
示例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();
}
}
}