Concurrency 用Clojure进行服务器编程
如何在Clojure中实现10k连接echo服务器Concurrency 用Clojure进行服务器编程,concurrency,clojure,Concurrency,Clojure,如何在Clojure中实现10k连接echo服务器 clojure.contrib.server-socket不是答案,因为它为每个连接包装了一个新的操作系统线程。clojure的好处是,您拥有所有这些适用于JVM的优秀库,它们都经过了高度优化、可配置和深思熟虑。像这样的事情应该会让你行动起来: (ns netty (:gen-class) (:import [java.net InetSocketAddress] [java.util.concurrent Exec
clojure.contrib.server-socket不是答案,因为它为每个连接包装了一个新的操作系统线程。clojure的好处是,您拥有所有这些适用于JVM的优秀库,它们都经过了高度优化、可配置和深思熟虑。像这样的事情应该会让你行动起来:
(ns netty
(:gen-class)
(:import
[java.net InetSocketAddress]
[java.util.concurrent Executors]
[org.jboss.netty.bootstrap ServerBootstrap]
[org.jboss.netty.channel Channels ChannelPipelineFactory
SimpleChannelHandler]
[org.jboss.netty.channel.socket.nio NioServerSocketChannelFactory]
[org.jboss.netty.buffer ChannelBuffers]))
(declare make-handler)
(defn start
"Start a Netty server. Returns the pipeline."
[port handler]
(let [channel-factory (NioServerSocketChannelFactory.
(Executors/newCachedThreadPool)
(Executors/newCachedThreadPool))
bootstrap (ServerBootstrap. channel-factory)
pipeline (.getPipeline bootstrap)]
(.addLast pipeline "handler" (make-handler))
(.setOption bootstrap "child.tcpNoDelay", true)
(.setOption bootstrap "child.keepAlive", true)
(.bind bootstrap (InetSocketAddress. port))
pipeline))
(defn make-handler
"Returns a Netty handler."
[]
(proxy [SimpleChannelHandler] []
(channelConnected [ctx e]
(let [c (.getChannel e)]
(println "Connected:" c)))
(channelDisconnected [ctx e]
(let [c (.getChannel e)]
(println "Disconnected:" c)))
(messageReceived [ctx e]
(let [c (.getChannel e)
cb (.getMessage e)
msg (.toString cb "UTF-8")]
(println "Message:" msg "from" c)))
(exceptionCaught
[ctx e]
(let [throwable (.getCause e)]
(println "@exceptionCaught" throwable))
(-> e .getChannel .close))))
您是指c10k问题吗?我读过,是的,我很好奇如何用这种有趣的语言实现它。请注意,clojure大量宣传其并发功能。谢谢!我在这里提出了一个简单的leiningen项目:如何向该服务器发送消息?@vemv我已经更新了repo,使用github项目使用公共netty,并添加了如何向服务器发送消息的示例。