Correct way to send data through a socket with NSOutputStream

后端 未结 2 357
不思量自难忘°
不思量自难忘° 2021-02-03 11:30

I am just getting started with socket programming on iOS and I am struggling to determine the use of the NSStreamEventHasSpaceAvailable event for NSOutputStre

2条回答
  •  感情败类
    2021-02-03 12:06

    You can write to a stream at any time, but for network streams, -write:maxLength: returns only until at least one byte has been written to the socket write buffer. Therefore, if the socket write buffer is full (e.g. because the other end of the connection does not read the data fast enough), this will block the current thread. If you write from the main thread, this will block the user interface.

    The NSStreamEventHasSpaceAvailable event is signalled when you can write to the stream without blocking. Writing only in response to that event avoids that the current thread and possibly the user interface is blocked.

    Alternatively, you can write to a network stream from a separate "writer thread".

提交回复
热议问题