python - 带有python客户端的Erlang回显服务器没有回显,python客户端没有正确接收响应
问题描述
所以我试图启动一个erlang服务器,它将从我的python客户端回显。我可以看到连接已经建立,但是回声实际上并没有发生。谁能指出我正确的解决方案?
我使用 python3 作为我的客户端驱动程序。
这是我的 erlang 服务器:我从 echo:accept(6000) 开始。
-module(echo).
-export([accept/1]).
%% Starts an echo server listening for incoming connections on
%% the given Port.
accept(Port) ->
{ok, Socket} = gen_tcp:listen(Port, [binary, {active, true}, {packet, line}, {reuseaddr, true}]),
io:format("Echo server listening on port ~p~n", [Port]),
server_loop(Socket).
%% Accepts incoming socket connections and passes then off to a separate Handler process
server_loop(Socket) ->
{ok, Connection} = gen_tcp:accept(Socket),
Handler = spawn(fun () -> echo_loop(Connection) end),
gen_tcp:controlling_process(Connection, Handler),
io:format("New connection ~p~n", [Connection]),
server_loop(Socket).
%% Echoes the incoming lines from the given connected client socket
echo_loop(Connection) ->
receive
{tcp, Connection, Data} ->
gen_tcp:send(Connection, Data),
echo_loop(Connection);
{tcp_closed, Connection} ->
io:format("Connection closed ~p~n", [Connection])
end.
这是我的python客户端:
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = ('localhost', 6000)
print(sys.stderr, 'connecting to %s port %s' % server_address)
sock.connect(server_address)
try:
# Send data
message = 'This is the message. It will be repeated.'
convertedString = message.encode('utf-8')
print(sys.stderr, 'sending "%s"' % message)
sock.sendall(convertedString)
# Look for the response
amount_received = 0
amount_expected = len(message)
while amount_received < amount_expected:
data = sock.recv(16).decode('utf-8')
amount_received += len(data)
print(sys.stderr, 'received "%s"' % data)
finally:
print(sys.stderr, 'closing socket')
sock.close()
我认为问题在于它只是在发送后挂起,现在它正在等待响应,我想我可能没有以正确的方式接收字符串。
解决方案
一个问题是您有{packet, line}
并且消息不包含新行,因此回显服务器在将消息发送到处理程序之前一直等待消息完成。
此外,您应该小心使用该active
选项,因为在调用期间收到的任何数据都controlling_process/2
将保留在前一个处理程序中。您应该启动接受的套接字,{active, false}
然后将其设置为true | pos_integer()
套接字由处理程序管理的时间。
推荐阅读
- public-key-encryption - 超核协议中使用的密钥方案是什么?
- php - PHP 架构 - 每个用户的单个 cron 作业
- angular - 角度拖放到不同的列表 Ionic
- azure - Continuous WebJob 随机重启
- google-apps-script - 复制满足条件的特定行,从一张纸到另一张
- javascript - 如何将 window.open 弹出窗口作为对话框
- c++ - asw-sdk-cpp initAPI 和 ShutDownAPI
- bash - 考虑特定的退出代码而不是失败并继续
- flutter - 如何在颤动的选项卡之间更改浮动操作按钮
- hibernate - org.hibernate.PropertyValueException:非空属性引用空值或瞬态值