erlang web服务器性能,C, Erlang, Java and Go四种语言的web服务器性能测试

本文介绍了如何使用Erlang编写的简单HTTP服务器示例,并展示了在单CPU和多核CPU模式下运行的方法。源代码来自Yufeng的博客,包括使用`erl`编译和任务设置指令。同时,提供了Java源代码片段,展示如何创建一个基于NIO的HTTP服务器和处理协议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Erlang hello world server

The source code is available at yufeng’s blog, see http://blog.yufeng.info/archives/105

Just copy the code after “cat ehttpd.erl”, and compile it.

$ erlc ehttpd.erl

$ taskset -c 1 erl +K true +h 99999 +P 99999 -smp enable +S 2:1 -s ehttpd

$ taskset -c 1-7 erl +K true -s ehttpd

We use taskset to limit erlang vm to use only 1 CPU/core or use all CPU cores. The 2nd line is run in single CPU mode, and the 3rd line is run in multi-core CPU mode.

Java source code, save the 2 class as HttpServer.java and HttpProtocolHandler.java, and do necessary import.

public class HttpServer {

public static void main(String[] args) throws Exception {

SocketAcceptor acceptor = new NioSocketAcceptor(4);

acceptor.setReuseAddress( true );

int port = 8080;

String hostname = null;

if (args.length > 1) {

hostname = args[0];

port = Integer.parseInt(args[1]);

}

// Bind

acceptor.setHandler(new HttpProtocolHandler());

if (hostname != null)

acceptor.bind(new InetSocketAddress(hostname, port));

else

acceptor.bind(new InetSocketAddress(port));

System.out.println("Listening on port " + port);

Thread.currentThread().join();

}

}

public class HttpProtocolHandler extends IoHandlerAdapter {

public void sessionCreated(IoSession session) {

session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

session.setAttribute(SslFilter.USE_NOTIFICATION);

}

public void sessionClosed(IoSession session) throws Exception {}

public void sessionOpened(IoSession session) throws Exception {}

public void sessionIdle(IoSession session, IdleStatus status) {}

public void exceptionCaught(IoSession session, Throwable cause) {

session.close(true);

}

static IoBuffer RESULT = null;

public static String HTTP_200 = "HTTP/1.1 200 OK\r\nContent-Length: 13\r\n\r\n" +

"hello world\r\n";

static {

RESULT = IoBuffer.allocate(32).setAutoExpand(true);

RESULT.put(HTTP_200.getBytes());

RESULT.flip();

}

public void messageReceived(IoSession session, Object message)

throws Exception {

if (message instanceof IoBuffer) {

IoBuffer buf = (IoBuffer) message;

int c = buf.get();

if (c == 'G' || c == 'g') {

session.write(RESULT.duplicate());

}

session.close(false);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值