我有客户端服务器设置,客户端在C#中,服务器在Java中。
现在我将字符串编码为字节数组并将其发送到Java服务器,但是当Java解码时,它会在每个字符后面收到一个带有空格的String
:
Sending PLAIN >>>>> Received P L A I N
C#代码(发件人):
static byte[] GetBytes(string str) {
byte[] bytes = Encoding.UTF8.GetBytes(str);
// System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
Java代码(接收方):
protected SaslResponse receiveSaslMessage() throws TTransportException {
underlyingTransport.readAll(messageHeader, 0, messageHeader.length);
byte statusByte = messageHeader[0];
// Bytes for C# code received here
byte[] payload = new byte[EncodingUtils.decodeBigEndian(messageHeader, STATUS_BYTES)];
underlyingTransport.readAll(payload, 0, payload.length);
NegotiationStatus status = NegotiationStatus.byValue(statusByte);
if (status == null) {
sendAndThrowMessage(NegotiationStatus.ERROR, "Invalid status " + statusByte);
} else if (status == NegotiationStatus.BAD || status == NegotiationStatus.ERROR) {
try {
String remoteMessage = new String(payload, "UTF-8");
throw new TTransportException("Peer indicated failure: " + remoteMessage);
} catch (UnsupportedEncodingException e) {
throw new TTransportException(e);
}
}
if (LOGGER.isDebugEnabled())
LOGGER.debug(getRole() + ": Received message with status {} and payload length {}",
status, payload.length);
return new SaslResponse(status, payload);
}
protected void handleSaslStartMessage() throws TTransportException, SaslException {
// call upper method
SaslResponse message = receiveSaslMessage();
LOGGER.debug("Received start message with status {}", message.status);
if (message.status != NegotiationStatus.START) {
sendAndThrowMessage(NegotiationStatus.ERROR, "Expecting START status, received " + message.status);
}
// Bytes converted to string here - Received P L A I N
String mechanismName = new String(message.payload);
TSaslServerDefinition serverDefinition = serverDefinitionMap.get(mechanismName);
LOGGER.debug("Received mechanism name '{}'", mechanismName);
if (serverDefinition == null) {
sendAndThrowMessage(NegotiationStatus.BAD, "Unsupported mechanism type " + mechanismName);
}
SaslServer saslServer = Sasl.createSaslServer(serverDefinition.mechanism,
serverDefinition.protocol, serverDefinition.serverName, serverDefinition.props,
serverDefinition.cbh);
setSaslServer(saslServer);
}
答案 0 :(得分:0)
首先将调试添加到C#代码中:
static byte[] GetBytes(string str) {
byte[] bytes = Encoding.UTF8.GetBytes(str);
// System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
Console.WriteLine("Base64 debug: " + Convert.ToBase64String(data));
return bytes;
}
然后将其转换为Java代码:
// Bytes converted to string here - Received P L A I N
System.out.println("Base64 debug: " + new sun.misc.BASE64Encoder().encode(message.payload));
String mechanismName = new String(message.payload);
最后替换:
//String mechanismName = new String(message.payload);
String mechanismName = new String(message.payload, "UTF-8");