[英]Erlang echo server with python client is not echoing, python client not receiving response correctly
所以我試圖啟動一個 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()
true | pos_integer()
當套接字由處理程序管理時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.