有几多日未写erlang学习代码了。
前一段时间主要做了项目的优化,有几点效果挺不错,这里略提一下。
io很耗时,日志通过udp远程写到其它服务器上,会大量减少cpu的消耗。
nosql概念在游戏开中很合适,使用json或protobuf直接存储在key-value数据库中非常方便,采用后基本上无需任何持久层的工作量。而且nosql的设计方式对某些特定场景的处理可大幅提高性能,比如:以前查询玩家的信件,直接使用sql查询,需要查询整张表,采用nosql的设计方式,在玩家中存储一个数组,里面是信件的id,可以直接根据id去查询数据。
好了,来看erlang test7
-module(test7). -export([start/0]). start()-> {ok,ListenSocket} = gen_tcp:listen(8889,[binary,{packet,2},{reuseaddr,true},{active,true}]), listen_tcp(ListenSocket), gen_tcp:close(ListenSocket), io:format("start end."). listen_tcp(ListenSocket)-> {ok,Socket}=gen_tcp:accept(ListenSocket), spawn_link(fun()-> socket_rec(Socket) end), listen_tcp(ListenSocket). socket_rec(Socket)-> receive {tcp,Socket,Data}-> io:format("receive data ~n"), socket_rec(Socket); {tcp_closed,Socket}-> io:format("tcp_closed ~n"), gen_tcp:close(Socket); {tcp_error,Socket,Reason}-> io:format("tcp_error ~n"), gen_tcp:close(Socket) end.
test7,打开一个socket监听端口,然后开启一个线程去处理接收数据。
好了,继续测试半主动式:接一个包,设置socket为不接收状态,然后处理完包后,再继续读取数据包。
如果开启了新的线程来接收数据。别忘记调用:
controlling_process(Socket, Pid) -> ok | {error, Reason}
Assigns a new controlling process Pid to Socket. The controlling process is the process which receives messages from the socket. If called by any other process than the current controlling process, {error, not_owner} is returned.
他的作用是把一个新的线程和这个socket绑定,这样新线程可以接收到socket的数据。
也让我困惑了两天为什么接收不到数据。
0 条评论。