java实现io阻塞的代码,Java:完整的每个连接线程阻塞IO与NIO的代码示例?

如果您正在使用NIO,我还建议您使用框架.我一直在使用

Apache Mina,我会推荐它.

至于阻塞IO,基本上你需要一个监听器线程来接受传入的连接并产生将处理每个连接的其他线程.下面是一个这样的Listener代码的示例,最初是为Apache Felix Project提供的.

如果您查找完整但已修改的版本,则可以使用browse the source here.

例如

/*

* Licensed to the Apache Software Foundation (ASF) under one or more

* contributor license agreements. See the NOTICE file distributed with

* this work for additional information regarding copyright ownership.

* The ASF licenses this file to You under the Apache License, Version 2.0

* (the "License"); you may not use this file except in compliance with

* the License. You may obtain a copy of the License at

*

* http://www.apache.org/licenses/LICENSE-2.0

*

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.

*/

package org.apache.felix.shell.remote;

import java.io.IOException;

import java.io.PrintStream;

import java.net.ServerSocket;

import java.net.Socket;

import java.net.SocketException;

/**

* Implements a simple listener that will accept a single connection.

*

*

* @author Dieter Wimberger (wimpi)

*/

class Listener

{

private int m_Port;

private Thread m_ListenerThread;

private boolean m_Stop = false;

private ServerSocket m_ServerSocket;

private AtomicInteger m_UseCounter;

private int m_MaxConnections;

/**

* Activates this listener on a listener thread (telnetconsole.Listener).

*/

public void activate()

{

//configure from system property

try

{

m_Port = Integer.parseInt( System.getProperty( "osgi.shell.telnet.port", "6666" ) );

}

catch ( NumberFormatException ex )

{

Activator.getServices().error( "Listener::activate()", ex );

}

try

{

m_MaxConnections = Integer.parseInt( System.getProperty( "osgi.shell.telnet.maxconn", "2" ) );

}

catch ( NumberFormatException ex )

{

Activator.getServices().error( "Listener::activate()", ex );

}

m_UseCounter = new AtomicInteger( 0 );

m_ListenerThread = new Thread( new Acceptor(), "telnetconsole.Listener" );

m_ListenerThread.start();

}//activate

/**

* Deactivates this listener.

*

* The listener's socket will be closed, which should cause an interrupt in the

* listener thread and allow for it to return. The calling thread joins the listener

* thread until it returns (to ensure a clean stop).

*/

public void deactivate()

{

try

{

m_Stop = true;

//wait for the listener thread

m_ServerSocket.close();

m_ListenerThread.join();

}

catch ( Exception ex )

{

Activator.getServices().error( "Listener::deactivate()", ex );

}

}//deactivate

/**

* Class that implements the listener's accept logic as a Runnable.

*/

private class Acceptor implements Runnable

{

/**

* Listens constantly to a server socket and handles incoming connections.

* One connection will be accepted and routed into the shell, all others will

* be notified and closed.

*

* The mechanism that should allow the thread to unblock from the ServerSocket.accept() call

* is currently closing the ServerSocket from another thread. When the stop flag is set,

* this should cause the thread to return and stop.

*/

public void run()

{

try

{

/*

A server socket is opened with a connectivity queue of a size specified

in int floodProtection. Concurrent login handling under normal circumstances

should be handled properly, but denial of service attacks via massive parallel

program logins should be prevented with this.

*/

m_ServerSocket = new ServerSocket( m_Port, 1 );

do

{

try

{

Socket s = m_ServerSocket.accept();

if ( m_UseCounter.get() >= m_MaxConnections )

{

//reject with message

PrintStream out = new PrintStream( s.getOutputStream() );

out.print( INUSE_MESSAGE );

out.flush();

//close

out.close();

s.close();

}

else

{

m_UseCounter.increment();

//run on the connection thread

Thread connectionThread = new Thread( new Shell( s, m_UseCounter ) );

connectionThread.start();

}

}

catch ( SocketException ex )

{

}

}

while ( !m_Stop );

}

catch ( IOException e )

{

Activator.getServices().error( "Listener.Acceptor::activate()", e );

}

}//run

}//inner class Acceptor

private static final String INUSE_MESSAGE = "Connection refused.\r\n"

+ "All possible connections are currently being used.\r\n";

}//class Listener

您可以找到其他示例here和here.

请注意,当您有更多负载时,NIO优于阻塞模型的优势就会发挥作用.从某一点来看,线程创建,管理和上下文切换的额外工作量将限制您的系统性能.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值