经常要用到网络编程。目前常用的服务器端有的Socket编程,还有NIO编程。
针对NIO编程,这里选择了一个成熟的框架Netty来编写服务器端。
而Socket的Server端,采用线程池来构造,能满足日常的一般需求。
========== netty
EchoServer.java
import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.apache.log4j.Logger; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.Delimiters; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; public class EchoServer { private static final Logger LOGGER = Logger.getLogger(EchoServer.class); private static final int PORT = 10007; private static final String FRAMER = "framer"; private static final String DECODER = "decoder"; private static final String ENCODER = "encoder"; private static final String HANDLER = "handler"; /** * @param args */ public static void main(String[] args) { LOGGER.info("start netty echo server."); ChannelFactory factory = new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ServerBootstrap bootstrap = new ServerBootstrap(factory); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast(FRAMER, new DelimiterBasedFrameDecoder( Integer.MAX_VALUE, Delimiters.lineDelimiter())); pipeline.addLast(DECODER, new StringDecoder()); pipeline.addLast(ENCODER, new StringEncoder()); pipeline.addLast(HANDLER, new EchoServerHandler()); return pipeline; } }); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); bootstrap.bind(new InetSocketAddress(PORT)); } }
EchoServerHandler.java
import java.util.concurrent.atomic.AtomicInteger; import org.apache.log4j.Logger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelHandler; import com.alibaba.fastjson.JSON; public class EchoServerHandler extends SimpleChannelHandler { private static final Logger LOGGER = Logger.getLogger(EchoServer.class); private static final AtomicInteger COUNT = new AtomicInteger(); @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { String inputString = (String) e.getMessage(); try { TransportMessage request = JSON.parseObject(inputString, TransportMessage.class); String response = null; if (request.getCode() % 2 == 0) { response = JSON.toJSONString(new TransportMessage(7100, "request.getState()%2 == 0" + request.getContent())); } else { response = JSON.toJSONString(new TransportMessage(8100, request .getContent())); } Channel channel = e.getChannel(); byte[] arr = new StringBuilder(response).append("\tcount:") .append(COUNT.getAndIncrement()).append("\n").toString() .getBytes(); ChannelBuffer word = ChannelBuffers.buffer(arr.length); word.writeBytes(arr); channel.write(word); if (LOGGER.isDebugEnabled()) { LOGGER.debug(Thread.currentThread().getName() + ":" + e.getRemoteAddress() + " receives message : " + inputString + " -- send message : " + response); } System.out.println(Thread.currentThread().getName() + ":" + e.getRemoteAddress() + " receives message : " + inputString + " -- send message : " + response); } catch (Exception e1) { LOGGER.error("Error:" + e.getMessage(), e1); } } @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } @Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { LOGGER.error("Error:" + e.getCause().getMessage(), e.getCause()); Channel ch = e.getChannel(); ch.close(); } }
TransportMessage.java
public class TransportMessage { private int code; private String content; public TransportMessage(int code, String content) { super(); this.code = code; this.content = content; } public TransportMessage() { super(); } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public int hashCode() { final int prime = 37; int result = 17; result = prime * result + code; result = prime * result + ((content == null) ? 0 : content.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TransportMessage other = (TransportMessage) obj; if (code != other.code) return false; if (content == null) { if (other.content != null) return false; } else if (!content.equals(other.content)) return false; return true; } @Override public String toString() { return "TransportMessage [code=" + code + ", content=" + content + "]"; } }
======== socket server (with thread pool)
SocketServer.java
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; public class SocketServer implements Runnable { private final String name; private final ServerSocket server; private final BlockingQueue<Socket> queue; public SocketServer(String name, BlockingQueue<Socket> queue, int port) throws IOException { super(); this.name = name; this.server = new ServerSocket(port); this.server.setReuseAddress(true); this.queue = queue; System.out.println(server + " start to run."); } @Override public void run() { Thread.currentThread().setName(name); while (true) { try { queue.put(server.accept()); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { int port = 7777; int threadPoolSize = Runtime.getRuntime().availableProcessors() * 6; BlockingQueue<Socket> queue = new LinkedBlockingQueue<Socket>(); ExecutorService exec = Executors.newCachedThreadPool(); exec.execute(new SocketServer("producer", queue, port)); for (int i = 0; i < threadPoolSize; i++) { exec.execute(new Consumer(queue, "consumer-" + i)); } exec.shutdown(); } }
Consumer.java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import com.alibaba.fastjson.JSON; public class Consumer implements Runnable { private static final AtomicInteger count = new AtomicInteger(); private final BlockingQueue<Socket> queue; private final String name; public Consumer(BlockingQueue<Socket> queue, String name) { super(); this.queue = queue; this.name = name; } public void run() { Thread.currentThread().setName(name); System.out.println(name + " start to run."); while (true) { try { consume(queue.take()); } catch (Exception e) { e.printStackTrace(); } } } private void consume(Socket socket) throws IOException { try { socket.setTcpNoDelay(true); BufferedReader br = getReader(socket); PrintWriter pw = getWriter(socket); for (String msg = br.readLine(); msg != null; msg = br.readLine()) { System.out.println(Thread.currentThread().getName() + " receive msg : " + msg + " from " + socket.getRemoteSocketAddress() + ":" + socket.getPort()); String response = echoMsg(msg); pw.println(response); pw.flush(); System.out.println(Thread.currentThread().getName() + " send msg: " + response); if (msg.equalsIgnoreCase("bye")) { break; } } } finally { if (null != socket) { try { socket.close(); System.out.println(Thread.currentThread().getName() + " closes " + socket); } catch (IOException e) { e.printStackTrace(); } } } } private PrintWriter getWriter(Socket socket) throws IOException { return new PrintWriter(socket.getOutputStream()); } private BufferedReader getReader(Socket socket) throws IOException { return new BufferedReader( new InputStreamReader(socket.getInputStream())); } private String echoMsg(String request) { TransportMessage msg = JSON .parseObject(request, TransportMessage.class); return msg.getCode() + " --> world_" + count.getAndIncrement(); } }
=== socket client
SocketClient.java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import com.alibaba.fastjson.JSON; public class SocketClient { private final Socket socket; public SocketClient(String host, int port) throws UnknownHostException, IOException { this.socket = new Socket(host, port); this.socket.setTcpNoDelay(true); this.socket.setTrafficClass(0x08 | 0x10); this.socket.setReuseAddress(true); } private PrintWriter getWriter(Socket socket) throws IOException { return new PrintWriter(socket.getOutputStream()); } private BufferedReader getReader(Socket socket) throws IOException { return new BufferedReader( new InputStreamReader(socket.getInputStream())); } private void talk() { try { BufferedReader br = getReader(socket); PrintWriter pw = getWriter(socket); for (int i = 0; i < 100; i++) { TransportMessage tm = new TransportMessage(i, "Hello_" + i); String msg = JSON.toJSONString(tm); pw.println(msg); pw.flush(); System.out.println("send msg : " + msg); System.out.println("receive msg : " + br.readLine()); } } catch (Exception e) { e.printStackTrace(); } finally { if (null != socket) { try { socket.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } public static void main(String[] args) throws UnknownHostException, IOException { String host = "192.168.123.53"; int port = 7777; // int port = 10007; for (int i = 0; i < 100000; i++) { new SocketClient(host, port).talk(); } } }
相关推荐
Socket编程是网络通信的基础,而Netty则为构建基于Socket的服务端提供了强大的支持。 Netty的核心在于其使用了非阻塞I/O(Non-blocking I/O,也称为NIO)模型,这使得它在处理大量并发连接时表现出色。NIO是一种I/O...
学习Netty,可以从基础的Socket编程开始,然后深入理解Java NIO的基本概念,接着熟悉Netty提供的各种组件和API,通过编写简单的服务端和客户端程序来实践。随着对Netty的理解加深,可以尝试实现更复杂的网络应用,如...
标题"Netty技术文档,Socket技术,多线程"指出我们要讨论的是Netty框架,它与Socket编程以及多线程技术的结合。Netty是一个高性能、异步事件驱动的网络应用程序框架,用于快速开发可维护的高性能协议服务器和客户端...
Java Socket网络编程是Java平台中实现网络通信的核心技术,它基于传输层协议TCP和UDP,为应用程序提供了低级别的、原始的比特流服务。本基础示例将深入探讨这两种协议下的Socket编程。 首先,TCP(Transmission ...
《多线程并发编程在Netty中的应用分析》 在当今高性能网络编程领域,Netty以其高效、灵活和易用的特性,成为了许多系统开发的首选框架。本篇内容将深入探讨多线程并发编程在Netty中的核心应用,帮助读者理解如何...
标题中的“Netty实现Java服务端和C#客户端联通”是指使用Netty作为Java服务器框架,与C#客户端(使用DotNetty库)进行通信的一种技术实现。这涉及到跨平台的网络通信,以及两个不同编程语言间的交互。 Netty是Java...
本示例“Android-netty和socket通信的demo”将展示如何在Android平台上利用Netty进行网络通信,与传统的Socket编程相结合,实现更加灵活和高效的通信机制。 首先,理解Netty的基本概念是非常重要的。Netty是一个...
在本文中,我们将深入探讨Netty如何利用Socket编程实现服务端与客户端的通信,并通过示例代码来展示其具体实现过程。 首先,Socket编程是网络通信的基础,它提供了进程间的通信能力,允许不同计算机上的程序之间...
SpringBoot 2.0带来了许多改进,包括性能提升、更好的错误处理、对Java 9的支持以及对WebFlux的支持,后者是Spring提供的反应式编程模型。在本项目中,SpringBoot作为基础框架,用于搭建服务器环境,处理HTTP请求,...
这个项目涉及到的技术栈广泛,从服务器端的Java编程到客户端的C++编程,再到网络通信协议,都需要深入理解和实践。开发者需要具备扎实的网络基础知识、熟悉Java和C++编程,以及对ProtoBuf和Netty的运用能力。
该项目为基于Java语言的Socket编程学习项目,集成Mina和Netty框架,源代码库包含76个文件,其中Java源文件52个,XML配置文件15个,YAML配置文件5个,Git忽略文件1个,LICENSE文件1个,YAML文件1个,Markdown文件1个...
这个socket通信比较直观,比较容易看懂,实现了Java中的socket的通信问题。是Java网络编程的一个比较不错的例子!
Java作为一种广泛使用的编程语言,提供了丰富的API来支持网络编程,而Netty则是一个高性能、异步事件驱动的网络应用框架,用于快速开发可维护的高性能协议服务器和客户端。 在Java中,基础的网络编程通常依赖于`...
Java Socket编程是Java网络编程的基础,它提供了网络通信的能力,使得程序可以与其他计算机上的服务进行交互。在本案例中,我们将关注如何使用Java Socket来实现SMTP(Simple Mail Transfer Protocol)邮件发送,并...
学习Socket到Netty的转变,对于Java开发者来说,意味着从基础的网络编程跃升至高性能网络应用开发的领域。Netty的广泛应用包括游戏服务器、金融系统、大数据传输等,熟练掌握Netty能提升开发效率,构建出更稳定、更...
标题中的“基于Java开发的一款基于Netty的内网穿透工具”揭示了我们正在讨论的是一个使用Java编程语言,并且依赖于Netty框架的软件应用。Netty是一个高性能、异步事件驱动的网络应用程序框架,常用于开发服务器和...
在本文中,我们将深入探讨Netty与传统Socket编程的交互实例,这对于理解如何在实际项目中整合这两种技术至关重要。 首先,让我们了解Netty的核心特性。Netty采用了非阻塞I/O模型,这使得它在处理大量并发连接时表现...
Java的Socket编程是网络编程的基础,它允许两个网络应用程序之间建立通信链接,进行数据传输。在Java中,Socket是java.net包的一部分,提供了客户端/服务器通信的基本接口。本篇文章将深入探讨Socket编程的基础知识...
此外,课程可能还会涉及其他高级主题,如NIO(非阻塞I/O)、Netty框架、WebSocket协议等,这些都是现代Java网络编程中不可或缺的部分。 总的来说,"java网络编程课件.zip"是一个全面的教程,可以帮助学习者从基础到...
netty 2019 最新源码, 包含示例 Netty是一个java开源框架。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发...Netty相当简化和流线化了网络应用的编程开发过程,例如,TCP和UDP的socket服务开发。