我正在开发一个使用NSStream和套接字与Java客户端对话的iOS应用程序。
他们彼此交谈很好,但在iOS方面,我经常会在收到的字符串末尾注销一些奇怪的字符。另一方面,Java客户端似乎正在阅读iOS应用程序发送的所有内容。
垃圾字符的模式长度在5到30个字符之间,它们的图案看起来非常相似。它们总是包含许多颠倒的问号。
我已经包含了我的代码。有谁知道我做错了什么,或者如何消除这些不想要的角色?
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
{
switch (streamEvent) {
case NSStreamEventHasBytesAvailable: {
uint8_t buffer[100];
[(NSInputStream *)theStream read:buffer maxLength:sizeof(buffer)];
NSString *s = [[NSString alloc] initWithBytes:buffer length:100 encoding:NSASCIIStringEncoding];
if (s.length>1) {
CLS_LOG(@"Read: %@",s);
[self handleRecievedMessage:s];
}
并在Java服务器上
DataOutputStream out;
out = new DataOutputStream(socket.getOutputStream());
byte[] msg = messageToSend.getBytes();
out.write(msg);
答案 0 :(得分:1)
您应该正确处理实际从流中读取的字符数。试试这个代替你拥有的两条线:
NSInteger len = [(NSInputStream *)theStream read:buffer maxLength:sizeof(buffer)];
NSString *s = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
答案 1 :(得分:0)
rmaddy对于我正在从流中读取多少问题是正确的。这是我现在使用的代码,它不再读取任何垃圾字符。
- (void)readFromStream{
int BUFFER_LEN = 512;
uint8_t *buffer;
NSUInteger length;
BOOL freeBuffer = NO;
// The stream has data. Try to get its internal buffer instead of creating one
if(![inputStream getBuffer:&buffer length:&length]) {
// The stream couldn't provide its internal buffer. We have to make one ourselves
buffer = malloc(BUFFER_LEN * sizeof(uint8_t));
freeBuffer = YES;
NSInteger result = [inputStream read:buffer maxLength:BUFFER_LEN];
length = result;
}
if (buffer != NULL) {
NSString *s = [[NSString alloc] initWithBytes:buffer length:length encoding:NSASCIIStringEncoding];
if (s.length>1) {
CLS_LOG(@"Read: %@",s);
[self handleRecievedMessage:s];
}
}
// length bytes of data in buffer
if(freeBuffer) free(buffer);
}