解决方法
我正在使用Netty来实现类似的方案.它只是工作!
以下是使用netty的起点:
public class TCPListener { private static ServerBootstrap bootstrap; public static void run(){ bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(),Executors.newCachedThreadPool())); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { TCPListnerHandler handler = new MyHandler(); ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("handler",handler); return pipeline; } }); bootstrap.bind(new InetSocketAddress(9999)); //port number is 9999 } public static void main(String[] args) throws Exception { run(); } }
和MyHandler类:
public class MyHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived( ChannelHandlerContext ctx,MessageEvent e) { try { String remoteAddress = e.getRemoteAddress().toString(); ChannelBuffer buffer= (ChannelBuffer) e.getMessage(); //Now the buffer contains byte stream from client. } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } byte[] output; //suppose output is a filled byte array ChannelBuffer writebuffer = ChannelBuffers.buffer(output.length); for (int i = 0; i < output.length; i++) { writebuffer.writeByte(output[i]); } e.getChannel().write(writebuffer); } @Override public void exceptionCaught( ChannelHandlerContext ctx,ExceptionEvent e) { // Close the connection when an exception is raised. e.getChannel().close(); } }