1
我有客戶端服務器設置,客戶端使用C#,服務器使用Java。 現在我編碼的字符串轉換成字節數組,並將其發送到Java服務器,但是當爪哇解碼它接收到一個String
與每個字符之後的空間:在c#中將字符串轉換爲字節數組並將字節數組轉換爲java中的字符串
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);
}
我認爲你應該使用'UTF8',不'UTF8'字符串,即'字符串remoteMessage =新的字符串(有效載荷,「UTF8」);' – dasblinkenlight 2014-10-05 10:19:19
C#追加'nul'字符,即'\ 0'? – 2014-10-05 10:22:39
我懷疑c#是否添加它們,但可以使用十六進制編輯器輕鬆檢查它? – Noctis 2014-10-05 10:35:02