返回信息流时不时会需要写一个socket server。但是觉得这么常用的东西应该被人写烂了吧,有没有常用的稳定的实现呢?
这是一条镜像帖。来源:北邮人论坛 / java / #16908同步于 2010/12/16
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
Java有没有类似python的SocketServer一样的类?
wks
2010/12/16镜像同步9 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
你说的是python里那个通过HTTP方式共享文件的SimpleSocketServer么。。是这么拼的吧。。。大概
【 在 wks (cloverprince) 的大作中提到: 】
: 时不时会需要写一个socket server。但是觉得这么常用的东西应该被人写烂了吧,有没有常用的稳定的实现呢?
Python那个可以共享文件的是SimpleHTTPServer。
但我要的不是这个。我要的是SocketServer(Python里就叫这个名字)。具体的是SocketServer.ThreadingTCPServer。或者Python里的asyncore里的东东(帮你select,你只写遇到read,write,accept,close事件的时候怎么办)。
我时不时的会写几个bug百出的用Thread实现的TCP Socket服务器。但是也懒得维护自己的TCP服务器。
或者说,在这个HTTP泛滥成灾的年代,大家都直接用Jetty,不屑TCP了?
【 在 ox 的大作中提到: 】
: 你说的是python里那个通过HTTP方式共享文件的SimpleSocketServer么。。是这么拼的吧。。。大概
: 【 在 wks (cloverprince) 的大作中提到: 】
: : 时不时会需要写一个socket server。但是觉得这么常用的东西应该被人写烂了吧,有没有常用的稳定的实现呢?
: ...................
sf上找找吧。。。
我没用过。。
【 在 wks (cloverprince) 的大作中提到: 】
: Python那个可以共享文件的是SimpleHTTPServer。
: 但我要的不是这个。我要的是SocketServer(Python里就叫这个名字)。具体的是SocketServer.ThreadingTCPServer。或者Python里的asyncore里的东东(帮你select,你只写遇到read,write,accept,close事件的时候怎么办)。
: 我时不时的会写几个bug百出的用Thread实现的TCP Socket服务器。但是也懒得维护自己的TCP服务器。
: ...................
挖一下自己的坟。
Netty是一个基于NIO的Socket Server/Client框架。用法类似Python的Twisted。
类似Socket/Channel建立、绑定、监听、接受、读写、关闭、连接、发送、Select/Pool,还有多线程、异常处理等一系列琐碎的事情,都帮用户处理了。用户只需要覆盖几个重载函数(比如处理具体接收到的数据等)就可以了。
开源软件,Apache License。
地址:http://www.jboss.org/netty
下面是一个简单的echo服务器(用户发来什么就发回去什么)
package netty;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
class EchoServerHandler extends SimpleChannelHandler {
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
Channel ch = e.getChannel();
ch.write(e.getMessage());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
e.getCause().printStackTrace();
Channel ch = e.getChannel();
ch.close();
}
}
public class EchoServer {
public static void main(String[] args) {
ChannelFactory factory = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
ServerBootstrap bootstrap = new ServerBootstrap(factory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() {
return Channels.pipeline(new EchoServerHandler());
}
});
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.bind(new InetSocketAddress(8080));
}
}
jetty仅限于http。http并不适合做所有的事。也有一定的overhead。
【 在 UnrealT 的大作中提到: 】
: 用jetty有啥不好
: --
嗯,据说是同一个作者写的。
【 在 UnrealT 的大作中提到: 】
: 原来你要非HTTP
: 还有个Apache MINA,这个比较好使
: --
: ...................