德国Umlaute的问题,从SWI Prolog到JAVA的TCPIP

时间:2015-11-12 09:45:33

标签: java prolog tcp-ip ffi swi-prolog

我尝试在Prolog服务器应用程序和Java客户端应用程序之间实现tcpip连接。它有效,但我有问题,我没有正确收到德国元音(ä,ü等)。这就是我所做的:

在Java中,客户端:

inputreader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(),"UTF-8" ));

...

StringBuilder sb = new StringBuilder();
String responseLine;
while ((responseLine = inputreader.readLine()) != null) {
    // System.out.println("Server: " + responseLine);

    // Character.toString ((char) i);
    sb.append(responseLine);
    if( responseLine.indexOf( ".") != -1 && responseLine.length() == 1 ){
       break;
    }
}

在SWI Prolog中,服务器端:

:- set_prolog_flag(encoding,utf8).

% based on http://swi-prolog.996271.n3.nabble.com/socket-communication-td1653.html
server(PortNumber) :-
    setup_call_cleanup(tcp_socket(S),  % no leaks, please
           (true; fail),
           tcp_close_socket(S)),
    tcp_bind(S, PortNumber),
    tcp_listen(S, 5),
    format('listen to portnumber ~w~n', [PortNumber]),
    server_loop(S).

server_loop(S) :-
    tcp_accept(S, S1, From),
    format('receiving traffic from: ~q~n', [From]),
    setup_call_cleanup(tcp_open_socket(S1, In, Out),
           server_operation(In, Out),
           (  writeln('closing...'),
              close(In),
              close(Out))), !,
    server_loop(S).

server_operation(In, Out) :-
    \+at_end_of_stream(In),
    read_pending_input(In, Codes, []), 
    atom_codes(Text,Codes),
    write('received from client: '),write(Text),nl,

    % job which has to be done in Prolog
    extract_fct_call( Text, Fname, ListOfIname, ListOfIcontent ),
    call_fct( Fname, ListOfIname, ListOfIcontent, XMLreply ),

    atom_codes( XMLreply, CodeReply ),
    % append defined EOM as \n.\n
    append( CodeReply, [10,46,10], CodeMessage ),
    format(Out, '~s', [Message]),
    flush_output(Out),
    server_operation(In, Out).

server_operation(_In, _Out).

所以,我认为定义两边的UTF-8编码都会这样做,但事实并非如此。我从“Gemüse”开始SWI Prolog方面,并在Java方面获得“Gemxse”。我尝试使用

发送ASCII代码
atom_codes( Message, CodeMessage ),
format(Out, '~s', [CodeMessage]),

和Java端

inputreader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(),"US-ASCII" ));

inputreader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(),"ASCII" ));

但结果不会改变。 我该怎么办?

非常感谢提前!

解决方案:

在CapelliC的帮助下,通过添加

解决了这个问题

set_stream(Stream,encoding(utf8))

server_operation(In, Out) :-
    set_stream(In, encoding(utf8)),
    set_stream(Out, encoding(utf8)),
    \+at_end_of_stream(In),
    ...

然后在Java应用程序中收到Umlaute(确保在项目的属性中,文本的编码也设置为UTF-8)。

1 个答案:

答案 0 :(得分:1)

stream_property(流,编码(编码))将允许您检查和更改Prolog端的编码。但是一旦你确认Prolog实际上默认为UTF-8,并且你对此感到满意,也许你应该调整Java接口,也许在每个IO操作上指定编码

byte[] utf8Bytes = s.getBytes("UTF-8");