gpt4 book ai didi

java - German Umlaute 的问题,从 SWI Prolog 到 JAVA 的 TCPIP

转载 作者:可可西里 更新时间:2023-11-01 02:34:28 26 4
gpt4 key购买 nike

我尝试在 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 编码就可以了,但事实并非如此。我从 SWI Prolog 端开始使用“Gemüse”并在 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(流,编码(utf8))

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

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

最佳答案

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

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

关于java - German Umlaute 的问题,从 SWI Prolog 到 JAVA 的 TCPIP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33668458/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com