代码拉取完成,页面将自动刷新
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();
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。