`

Setting Up Socket Streams

阅读更多

Articles

Setting Up Socket Streams

You can use the NSStream class to establish a socket connection and, with the stream object (or objects) created as a result, send data to and receive data from a remote host. You can also configure the connection for security.

<!-- This template is being used for both PDF and HTML. --><!-- TopicBook.pm uses this template for its miniTOCs, but needs a different title. -->

Contents:

Basic Procedure
Securing and Configuring the Connection
Initiating an HTTP Request

 

Basic Procedure

Setting up a socket connection is easy. Just send the NSStream class a getStreamsToHost:port:inputStream:outputStream: message and you will receive back an object representing an input stream from the remote host or an output stream to the remote host—or both input- and output-stream objects. The getStreamsToHost:port:inputStream:outputStream: class method merely requires you to provide an NSHost object (identifying the remote host) and a port number.

Listing 1 illustrates the use of getStreamsToHost:port:inputStream:outputStream:. This example shows the creation of both an NSInputStream object and an NSOutputStream object. If you want to receive only one of these objects, just specify nil as the parameter value for the unwanted object.

 

Listing 1  Setting up a network socket stream

 

- (IBAction)searchForSite:(id)sender 
{ 
    NSString *urlStr = [sender stringValue]; 
    if (![urlStr isEqualToString:@""]) { 
        [searchField setEnabled:NO]; 
        NSURL *website = [NSURL URLWithString:urlStr]; 
        if (!website) { 
            NSLog(@"%@ is not a valid URL"); 
            return; 
        } 
        NSHost *host = [NSHost hostWithName:[website host]]; 
        // iStream and oStream are instance variables 
        [NSStream getStreamsToHost:host port:80 inputStream:&iStream 
            outputStream:&oStream]; 
        [iStream retain]; 
        [oStream retain]; 
        [iStream setDelegate:self]; 
        [oStream setDelegate:self]; 
        [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] 
            forMode:NSDefaultRunLoopMode]; 
        [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] 
            forMode:NSDefaultRunLoopMode]; 
        [iStream open]; 
        [oStream open]; 
    } 
} 

 

Because the stream objects you receive back from getStreamsToHost:port:inputStream:outputStream: are autoreleased, be sure to retain them right away. If the socket connection fails, then one or both of the requested NSInputStream and NSOutputStream objects are nil. Then, as usual, set the delegate, schedule the stream on a run loop, and open the stream. The delegate should begin to receive stream-event messages (stream:handleEvent:). See “Reading From Input Streams” and “Writing To Output Streams” for more information.

 

Securing and Configuring the Connection

Before you open a stream object, you might want to set security and other features for the connection to the remote host (which might be, for example, an HTTPS server). NSStream defines properties that affect the security of TCP/IP socket connections in two ways:

  • Secure Socket Layer (SSL).

    A security protocol using digital certificates to provide data encryption, server authentication, message integrity, and (optionally) client authentication for TCP/IP connections.

  • SOCKS proxy server.

    A server that sits between a client application and a real server over a TCP/IP connection. It intercepts requests to the real server and, if it cannot fulfill them from a cache of recently requested files, forwards them to the real server. SOCKS proxy servers help improve performance over a network and can also be used to filter requests.

For SSL security, NSStream defines various security-level properties (for example, NSStreamSocketSecurityLevelSSLv2). You set these properties by sending setProperty:forKey: to the stream object using the key NSStreamSocketSecurityLevelKey, as in this sample message:

 

[iStream setProperty:NSStreamSocketSecurityLevelTLSv1 forKey:NSStreamSocketSecurityLevelKey];

You must set the property before you open the stream. Once it opens, it goes through a handshake protocol to find out what level of SSL security the other side of the connection is using. If the security level is not compatible with the specified property, the stream object generates an error event. However, if you request a negotiated security level (NSStreamSocketSecurityLevelNegotiatedSSL), the security level becomes the highest that both sides of the connection can implement. Still, if you try to set an SSL security level when the remote host is not secure, an error is generated.

To configure a SOCKS proxy server for a connection, you need to construct a dictionary with keys of the form NSStreamSOCKSProxyNameKey (for example, NSStreamSOCKSProxyHostKey). The value of each key is the SOCKS proxy setting that Name refers to. Then using setProperty:forKey:, set the dictionary as the value of the NSStreamSOCKSProxyConfigurationKey.

If you know the proxy-server settings, you can construct the dictionary yourself. But an easier way to get a dictionary of current proxy settings is to use the System Configuration framework. To use this API in your program, add SystemConfiguration.framework to your project and import the <SystemConfiguration/SystemConfiguration.h> header file. Next, as shown in Listing 2, call the function SCDynamicStoreCopyProxies and be sure to cast the returned CFDictionary value to an NSDictionary object. Then use this dictionary to set the NSStreamSOCKSProxyConfigurationKey property.

 

Listing 2  Setting a stream to the current SOCKS proxy settings

 

// ... 
NSDictionary *proxyDict = (NSDictionary *)SCDynamicStoreCopyProxies(NULL); 
[oStream setProperty:proxyDict forKey:NSStreamSOCKSProxyConfigurationKey]; 
// ... 

 

For a detailed example of using the System Configuration API to get SOCKS proxy settings, see Technical Q&A QA1234, “Accessing HTTPS Proxy Settings.”

 

Initiating an HTTP Request

If you are opening a connection to an HTTP server (that is, a website), then you may have to initiate a transaction with that server by sending it an HTTP request. A good time to make this request is when the delegate of the NSOutputStream object receives a NSStreamEventHasSpaceAvailable event via a stream:handleEvent: message. Listing 3 shows the delegate creating an HTTP GET request and writing it to the output stream, after which it immediately closes the stream object.

 

Listing 3  Making an HTTP GET request

 

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode { 
    NSLog(@"stream:handleEvent: is invoked..."); 
  
    switch(eventCode) { 
        case NSStreamEventHasSpaceAvailable: 
        { 
            if (stream == oStream) { 
                NSString * str = [NSString stringWithFormat: 
                    @"GET / HTTP/1.0\r\n\r\n"]; 
                const uint8_t * rawstring = 
                    (const uint8_t *)[str UTF8String]; 
                [oStream write:rawstring maxLength:strlen(rawstring)]; 
                [oStream close]; 
            } 
            break; 
        } 
        // continued ... 
    } 
} 

 

Related Reference

 Objective-C

 

分享到:
评论

相关推荐

    Socket Streams Library-开源

    Socket Streams Library 是一个开源项目,它为 C++ 开发者提供了一个方便的接口,将标准库中的 IOStreams 功能扩展到了 POSIX 套接字上。这个库的主要目的是简化网络编程,尤其是涉及到套接字通信时的数据读写操作。...

    Ntfs Streams Editor2工具

    Ntfs数据流处理工具NtfsStreamsEditor提供了强大的搜索扫描能力,帮助找出危险所在;同时NtfsStreamsEditor提供了最强大的删除、附加、导入、导出、备份和还原等完整处理手段,是Ntfs数据流处理必备的工具。 Ntfs...

    Reactive Streams in Java: Concurrency with RxJava, Reactor, and Akka Streams

    Get an easy introduction to reactive streams in Java to handle concurrency, data streams, and the propagation of change in today's applications. This compact book includes in-depth introductions to ...

    Oracle Streams配置文档

    Oracle Streams是一种先进的数据复制解决方案,它允许用户在Oracle数据库之间实时传输数据,从而实现数据库的复制、归档、故障恢复和读写分离等多种功能。在本配置文档中,你将找到有关Oracle Streams的全面信息,...

    ios socket 编程的几种方式

    CFStream API是苹果提供的Core Foundation框架的一部分,可用于处理套接字流(socket streams)。这个API支持TCP和UDP协议,可以用于创建双向的数据流。CFStream创建的流可以是本地的(例如,与另一个进程通信)或...

    reactive-streams-1.0.3.jar

    reactive-streams-1.0.3.jar

    前端开源库-web-streams-polyfill

    `web-streams-polyfill` 是一个开源库,它实现了WHATWG 规范中的大部分 Web Streams API,使得开发者可以在不支持原生 Web Streams 的环境中也能使用这一强大的功能。这个库主要包含以下几个部分: 1. **...

    Kafka Streams in Action 高清文字版 非扫描版

    它的流处理组件Kafka Streams,允许用户在数据流进Kafka之后进行实时的流处理。Kafka Streams是一个轻量级的库,可以嵌入到任何Java应用程序中。使用Kafka Streams,开发者可以轻松地构建实时应用程序和微服务。 在...

    reactive-streams-1.0.3-API文档-中文版.zip

    赠送jar包:reactive-streams-1.0.3.jar; 赠送原API文档:reactive-streams-1.0.3-javadoc.jar; 赠送源代码:reactive-streams-1.0.3-sources.jar; 赠送Maven依赖信息文件:reactive-streams-1.0.3.pom; 包含...

    NtfsStreamsEditor2.rar

    在描述中提到的"NtfsStreamsEditor2.rar"是一个可能用于查看、编辑或提取这些隐藏NTFS流的工具。这类工具可以帮助安全研究人员、CTF挑战者或系统管理员探索系统中可能隐藏的信息。使用NtfsStreamsEditor2,用户可以...

    reactive-streams-1.0.3-API文档-中英对照版.zip

    赠送jar包:reactive-streams-1.0.3.jar; 赠送原API文档:reactive-streams-1.0.3-javadoc.jar; 赠送源代码:reactive-streams-1.0.3-sources.jar; 赠送Maven依赖信息文件:reactive-streams-1.0.3.pom; 包含...

    Kafka Streams1.zip

    《Kafka Streams实战》这本书是了解和掌握Apache Kafka的流处理框架Kafka Streams的重要资源。Kafka Streams是一个轻量级的库,允许开发者在Java或Scala应用中直接处理流数据,无需部署额外的集群服务。它将复杂的...

    Oracle Streams Step by Step PPT

    Oracle Streams 是Oracle数据库提供的一种强大的数据流和事件流解决方案,它允许在单个数据库内或跨多个数据库之间高效地移动数据和事件。Streams的核心功能包括数据捕获、传播和服务应用,支持显式(通过编程方式)...

    Reactive Streams in Java.pdf

    Reactive Streams in Java Concurrency with RxJava, Reactor, and Akka Streams. 2019年最新出版,清晰文字PDF,带目录书签。

    Streaming Architecture New Designs Using Apache Kafka and MapR Streams

    本文将深入探讨"Streaming Architecture New Designs Using Apache Kafka and MapR Streams"这一主题,阐述如何利用这两种强大的工具构建高效、可扩展的流处理系统。 Apache Kafka是一种分布式流处理平台,由...

    ntfsstreamseditor

    它引入了许多先进的特性,其中数据流(alternate data streams, ADS)是一个非常独特且在日常使用中不太为人所知的功能。"ntfsstreamseditor"是一款专门针对NTFS分区文件数据流进行操作的工具,它允许用户对数据流...

    reactive-streams-1.0.3-version.zip

    《Reactive Streams:异步流处理的基石》 在当今的高性能、高并发的Web应用程序开发中,异步编程已经成为了一种重要的模式。Reactive Streams是Java生态系统中为解决这一问题而诞生的一个标准,它旨在提供一种可...

    高清彩版 Kafka_Streams_in_Action

    ### 高清彩版 Kafka Streams in Action:深入解析 #### 一、背景介绍与书籍概述 《Kafka Streams in Action》是一本专为希望深入了解Kafka Streams及其在实时数据流处理应用中的实践而编写的书籍。作者Bill Bejeck...

Global site tag (gtag.js) - Google Analytics