网络服务器开发
serv = new TcpSocket();serv.listen();sock = serv.accept();
sock.read(buf); sock.write(buf); sock.close() |
p 一次服务
p 没有并发
p 短连接
p 有没有协议?
p
|
serv = new TcpSocket();serv.listen();while(1){
sock = serv.accept(); while(1){//重复服务单用户 sock.read(buf); sock.write(buf); } sock.close() } |
p 一次服务
p 没有并发
p 短连接
|
serv = new TcpSocket();serv.listen();while(1){
sock = serv.accept(); new Thread(){ while(1){//重复服务单用户 sock.read(buf); sock.write(buf); } sock.close() } } |
p 一次服务
p 没有并发
p 短连接
|
serv = new TcpSocket(); serv.listen();
select.add(serv, READ); // READ 表示只测试可读(读不阻塞)
while(1){
readable, writable = select.wait();
foreach(readable as sock){
if(sock == serv){
sock = serv.accept();
select.add(sock, READ);
}else{
sock.read(buf); sock.write(buf); sock.close();
}
}
// writable 为空, 因为我们不测试可写
}
sock.read(buf);
sock.write(buf); sock.close();
select.add(sock, WRITE);
foreach(writable as sock){
sock.write(buf);
sock.close();
}
报文设计
高层 | 文本, 带结束符 |
底层 | 二进制, 固定长度 |
Packet := Block+ '\n'
Block := Size Data
Size := literal_integer '\n'
Data := size_bytes_of_data '\n'
示例:
3
get
3
key
<回车>
优点
client = new Client(sock);
client.recv(packet);
client.send(packet);
client.close()
bytes = [];
while(1){
bytes += sock.read();
if(try_parse(bytes, &len) == READY){
// 已经解析出了一个报文, 报文的长度是len
// 从字节数组中清除掉已解析的
bytes.remove(len);
}
}
整合网络IO和报文解析
serv = new TcpSocket();serv.listen();sock = serv.accept();
client = new Client(sock); request = client.recv(); response = process(request); client.send(response); client.close() |
对于SSDB, LevelDB 相关的操作封装在 process 中. |