无法使用NSInputStream从iOS客户端读取Java服务器的响应

时间:2012-03-12 00:36:12

标签: java ios sockets client-server java-server

所有

这是我第一次在这里发帖 - 过去几天我搜索了几个小时。这不是我制作的第一个客户端/服务器应用程序,而且我完全不知道出了什么问题。

我有一台Java服务器(并且它能够正确地读取我的iOS客户端的请求 - 它甚至可以生成响应并且似乎正确发送,但是在iOS客户端上没有可读取的数据):

public void run() {
    BufferedReader in;

    try {
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        OutputStream out_stream = this.socket.getOutputStream();
        StringBuilder request = new StringBuilder();
        String request_buffer;

        while ((request_buffer = in.readLine()) != null) {
            request.append(request_buffer);
        }
        out_stream.write(processRequest(request.toString()).getBytes());
        out_stream.close();

        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

提供的Java函数作为生成它所属的类的实例的结果而被调用,并且它使用ServerSocket的accept()方法的结果进行初始化。一切似乎在这里工作正常 - 以下Python客户端能够发送请求(甚至读取响应):

DEFAULT_HOST = ''
DEFAULT_PORT = 2012
RECEIVE_BUFFER_SIZE = 4096

if __name__ == "__main__":
    import sys, socket

    port = DEFAULT_PORT
    host = DEFAULT_HOST
    if len(sys.argv) > 2:
        host = sys.argv[1]
        del sys.argv[1]

    if len(sys.argv) == 2:
            request = sys.argv[1]
            print "Requesting: %s" % request
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((host, port))
            s.send(request)
            s.shutdown(socket.SHUT_WR)

            response = ""
            message = True
            while message:
                message = s.recv(RECEIVE_BUFFER_SIZE)
                response += message

    print "Response: %s" % response

在发布iOS客户端之前,我已经使用以下Python服务器对其进行了测试(并且iOS客户端可以按预期读/写..这也适用于Python测试客户端):

import os, sys

DEFAULT_HOST = ''
DEFAULT_PORT = 4150

# Simple test server
DEFAULT_SIZE = 4096
import socket

class Server:

    def __init__(self, host, port, root, protocol, debug=True):
        self.debug = debug
        self.host = host
        self.port = port
        self.root = root
        self.protocol = protocol

    def __call__(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((self.host, self.port))
        s.listen(5)

        while True:
            try:
                c = s.accept()
                print "Connection: %s" % str(c)

                request = c[0].recv(DEFAULT_SIZE)
                print "Request: %s" % request

                try:
                    response = "test"
                    if self.debug:
                        print "Response: %s" % response

                except Exception as ex:
                    print "Error generating response: %s" % ex

                if response:
                    c[0].send(response)

                else:
                    c[0].send("3rr0rZ")

                c[0].close()
                print


            except Exception as ex:
                print ex


if __name__ == "__main__":
    host = DEFAULT_HOST
    port = DEFAULT_PORT

    args = sys.argv

    # choose a port
    if len(args) > 1 and args[1] == "-p":
        if len(args) < 3:
            raise Exception("Missing Argument for %s" % "-p")
            port = int(args[2])
            del args[1:3]
        else:
            port = DEFAULT_PORT

    # check if root specified
    if len(args) > 1:
        root = os.path.realpath(args[1])
        del args[1]
    else:
        root = os.getcwd()

    print "Using:"
    print "\tHost: %s" % host
    print "\tPort: %s" % port
    print "\tRoot: %s" % root
    print
    server = Server(host, port, root)
    server()

显然这是一个简化的服务器 - 问题不在于如何生成请求。对于更多背景,请求和响应是JSON字符串,但这并不完全相关。如前所述,Python客户端能够成功地从Java和Python服务器请求和接收响应。 iOS客户端可以成功地向Python和Java服务器发送请求,但它只能从Python服务器读取响应。这是iOS客户端的相关部分:

- (NSData *)sendMessage:(NSData *)request
{
    // Create low-level read/write stream objects
    CFReadStreamRef readStream = nil;
    CFWriteStreamRef writeStream = nil;

    // Create high-level stream objects
    NSInputStream *inputStream = nil;
    NSOutputStream *outputStream = nil;

    // Connect the read/write streams to a socket
    CFStreamCreatePairWithSocketToHost(nil, (__bridge CFStringRef) self.address, self.port, &readStream, &writeStream);

    // Create input/output streams for the raw read/write streams
    if (readStream && writeStream) {
        CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
        CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);

        inputStream = (__bridge_transfer NSInputStream *)readStream;
        [inputStream open];

        outputStream = (__bridge_transfer NSOutputStream *)writeStream;
        [outputStream open];
    }

    NSLog(@"Sending message to server: %@", request);
    [outputStream write:[request bytes] maxLength:[request length]];
    [outputStream close];

    int size;
    int buffer_size = 1024;
    uint8_t buffer[buffer_size];
    NSMutableData *response = [NSMutableData dataWithLength:0];
    while (![inputStream hasBytesAvailable]);

    NSLog(@"About to read");
    while ([inputStream streamStatus] == NSStreamStatusOpen)
    {        
        if ([inputStream hasBytesAvailable] && (size = [inputStream read:buffer maxLength:buffer_size]) > 0)
        {
            NSLog(@"Reading response data");
            [response appendData:[NSData dataWithBytes:buffer length:size]];
        }
    }

    NSLog(@"\tResponse:%@", response);
    return response;
}

从Java服务器读取时,iOS客户端永远不会越过以下行:

while (![inputStream hasBytesAvailable]);

我已经阅读了我可以找到的各种搜索字词的所有文档,论坛帖子,问题等,但没有任何帮助;我希望这里有人可以解决这个问题!我已经发布了我正在使用的代码的略微简化/扁平版本,但是,再次,这应该足以建立上下文..如果有必要,我会很乐意发布更多代码,并且我感谢任何帮助或洞察力你可以分享。

我故意不使用NSStreamDelegate,我无法想象这是一个问题。如果我是,我想象问题只会变成NSStreamEventHasBytesAvailable永远不会发生。

2 个答案:

答案 0 :(得分:2)

试试我的代码,它适用于我。

    NSInputStream *inputStream;
    NSOutputStream *outputStream;
    -(void) init{
        NSURL *website = [NSURL URLWithString:@"http://YOUR HOST"];

        CFReadStreamRef readStream;
        CFWriteStreamRef writeStream;
        CFStreamCreatePairWithSocketToHost(NULL,CFBridgingRetain([website host]),9876, &readStream, &writeStream);

        inputStream = (__bridge_transfer NSInputStream *)readStream;
        outputStream = (__bridge_transfer NSOutputStream *)writeStream;
        [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [outputStream open];
        [inputStream open];

        CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
        CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
    }

- (void) sendMessage {

    // it is important to add "\n" to the end of the line
    NSString *response  = @"Say hello to Ukraine\n";
    NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSUTF8StringEncoding]];
    int sent = [outputStream write:[data bytes] maxLength:[data length]];
    NSLog(@"bytes sent: %d",sent);

    do{
        uint8_t buffer[1024];
        int bytes = [inputStream read:buffer maxLength:sizeof(buffer)];
        NSString *output = [[NSString alloc] initWithBytes:buffer length:bytes encoding:NSUTF8StringEncoding];
        NSLog(@"%@",output);
    } while ([inputStream hasBytesAvailable]);
}

    public class ServerTest {
        public static void main(String[] args) {
            Thread thr = new Thread(new SocketThread());
            thr.start();
        }
    }

    class SocketThread implements Runnable {

        @Override
        public void run() {
            try {
                ServerSocket server = new ServerSocket(9876);
                while (true) {
                    new SocketConnection(server.accept()).start();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    class SocketConnection extends Thread {
        InputStream input;
        PrintWriter output;
        Socket socket;

        public SocketConnection(Socket socket) {
            super("Thread 1");
            this.socket = socket;
            try {
                input = socket.getInputStream();
                output = new PrintWriter(new OutputStreamWriter(
                        socket.getOutputStream()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                byte array[] = new byte[1024];
                while (true) {
                    do {
                        int readed = input.read(array);
                        System.out.println("readed == " + readed + " "
                                + new String(array).trim());
                        String sendString = new String(
                                "Hello Ukraine!".getBytes(),
                                Charset.forName("UTF-8"));
                        output.write(sendString);
                        output.flush();
                    } while (input.available() != 0);
                }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

答案 1 :(得分:0)

您的python服务器和Java服务器不等效。在python中,你会这样读:

request = c[0].recv(DEFAULT_SIZE)

在块中读取最多4096个字节。而在Java中你正在使用:

while ((request_buffer = in.readLine()) != null)

in.readLine()将阻塞,直到它结束行,或者直到它到达文件结尾。可能这会被卡住,直到客户端关闭套接字。您确定客户端正确关闭输出流吗?我不熟悉Objective C,但关闭输出流可能与关闭套接字的写入端不一样。

如果您负责线路的两侧,我会让客户端先写入一个长度标头(两个字节),然后再写入那么多的数据。然后服务器可以读取两个字节,计算剩余数据的长度,并读取那么多。

Length (2-bytes) | Data (length bytes)
----------------------------------------------------------
0x000C           | Hello World!

通过始终发送长度后跟数据,您甚至可以在不关闭套接字的情况下发送多条消息。