1 Star 0 Fork 0

PECman-李太素 / learning_ceylon

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
server_test.ceylon 2.08 KB
一键复制 编辑 原始数据 按行查看 历史
PECman 提交于 2018-05-05 07:52 . 更新 server_test.ceylon
import ceylon.http.server {
newServer,
Endpoint,
startsWith,
Response,
Request
}
import ceylon.http.server.websocket {
WebSocketEndpoint,
WebSocketChannel,
CloseReason
}
import ceylon.io {
SocketAddress
}
import ceylon.buffer.charset {
utf8
}
import ceylon.buffer {
ByteBuffer
}
//将List<Byte>转换为Array<Byte>
Array<Byte> listToArray<Byte>(List<Byte> list, Byte b) {
variable Integer a = 0;
value results = Array<Byte>.ofSize(list.size, b);
for(item in list) {
results.set(a, item);
a++;
}
return results;
}
void runServer() {
//创建一个HTTP服务器
value server = newServer {
//新的地址指向/hello
Endpoint {
path = startsWith("/hello");
//handle requests to this path
service(Request request, Response response)
=> response.writeString("Say more, more clear!");
},
WebSocketEndpoint {
path = startsWith("/websocket");
onOpen(WebSocketChannel channel)
=> print("Channel opened");
onClose(WebSocketChannel channel, CloseReason closeReason)
=> print("Channel closed");
void onError(WebSocketChannel webSocketChannel, Throwable? throwable) {}
void onText(WebSocketChannel channel, String text) {
print("Received text:");
print(text);
channel.sendText(text.uppercased);
}
void onBinary(WebSocketChannel channel, ByteBuffer binary) {
String data = utf8.decode(binary);
print("Received binary:");
print(data);
//utf8.encode函数无法返回ByteBuffer,但是BtyeBuffer的ofArray函数可以用一个数组初始化新对象
//List<Byte>暂时无法转换为Array<Byte>,我用listToArray实现了这一功能
//0.byte在这里无实际意义,只为了初始化listToArray里的数组所给定的默认值。
ByteBuffer encoded = ByteBuffer.ofArray(listToArray(utf8.encode(data.uppercased), 0.byte));
channel.sendBinary(encoded);
}
}
};
server.start(SocketAddress("127.0.0.1",8000));
}
shared void run() { //只有最高阶函数或类能被运行(shared)
runServer();
}
1
https://gitee.com/pecman/learning_ceylon.git
git@gitee.com:pecman/learning_ceylon.git
pecman
learning_ceylon
learning_ceylon
master

搜索帮助