다음을 시도하고 있습니다.
C # 클라이언트 :
string stringToSend = "Hello man";
BinaryWriter writer = new BinaryWriter(mClientSocket.GetStream(),Encoding.UTF8);
//write number of bytes:
byte[] headerBytes = BitConverter.GetBytes(stringToSend.Length);
mClientSocket.GetStream().Write(headerBytes, 0, headerBytes.Length);
//write text:
byte[] textBytes = System.Text.Encoding.UTF8.GetBytes(stringToSend);
writer.Write(textBytes, 0, textBytes.Length);
자바 서버 :
Charset utf8 = Charset.forName("UTF-8");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), utf8));
while (true) {
//we read header first
int headerSize = in.read();
int bytesRead = 0;
char[] input = new char[headerSize];
while (bytesRead < headerSize)
{
bytesRead += in.read(input, bytesRead, headerSize - bytesRead);
}
String resString = new String(input);
System.out.println(resString);
if (resString.equals("!$$$")) {
break;
}
}
문자열 크기는 9와 같습니다. 양쪽 모두 정확하지만 Java 쪽에서 문자열 자체를 읽을 때 데이터가 잘못 보입니다. char 버퍼 ( 'input'변수) 내용은 다음과 같습니다.
",",",'안녕하세요',''
바이트 배열을 뒤집어 엔디안을 변경하려고했습니다. 또한 ASCII와 UTF-8 사이의 문자열 인코딩 형식을 변경해 보았습니다. 여전히 엔디안 문제와 관련이있는 것처럼 느껴지지만 해결 방법을 알 수 없습니다. 스팀에 텍스트 데이터를 쓰기 위해 다른 유형의 작성자가 있지만 학습을 위해 원시 바이트 배열을 사용하려고합니다.
이들
byte[] headerBytes = BitConverter.GetBytes(stringToSend.Length);
4 바이트입니다. 그리고 그들은 문자 데이터가 아니므로 BufferedReader
. 바이트를 직접 읽으십시오.
byte[] headerBytes = new byte[4];
// shortcut, make sure 4 bytes were actually read
in.read(headerBytes);
이제 텍스트 길이를 추출하고 충분한 공간을 할당하십시오.
int length = ByteBuffer.wrap(headerBytes).getInt();
byte[] textBytes = new byte[length];
그런 다음 텍스트를 읽으십시오
int remaining = length;
int offset = 0;
while (remaining > 0) {
int count = in.read(textBytes, offset, remaining);
if (-1 == count) {
// deal with it
break;
}
remaining -= count;
offset += count;
}
이제 UTF-8로 디코딩하십시오.
String text = new String(textBytes, StandardCharsets.UTF_8);
그리고 당신은 끝났습니다.
엔디안은 처음 4 바이트와 일치해야합니다. 이를 확인하는 한 가지 방법은 "네트워크 순서"(big-endian)를 사용하는 것입니다. 그래서:
C # 클라이언트
byte[] headerBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(stringToSend.Length));
자바 서버
int length = ByteBuffer.wrap(headerBytes).order(ByteOrder.BIG_ENDIAN).getInt();
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다