iOS socket Stream

测试环境,mac osx 10.8

一:建立服务器端

由于mac osx10.8 已经集成 python2和 Twisted,我们可以直接利用此,构建一个简单的socket 服务器

如下测试一个简单的聊天 socket

并,定义,加入聊天时发送:iam:用户名

发送信息时:msg:信息

终端:vim server.py  回车,copy入如下代码

from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor class IphoneChat(Protocol):
def connectionMade(self):
self.factory.clients.append(self)
print "clients are ", self.factory.clients def connectionLost(self, reason):
self.factory.clients.remove(self) def dataReceived(self, data):
a = data.split(':')
print a
if len(a) > 1:
command = a[0]
content = a[1] msg = ""
if command == "iam":
self.name = content
msg = self.name + " has joined" elif command == "msg":
msg = self.name + ": " + content
print msg for c in self.factory.clients:
c.message(msg) def message(self, message):
self.transport.write(message + '\n') factory = Factory()
factory.clients = []
factory.protocol = IphoneChat
reactor.listenTCP(80, factory)
print "Iphone Chat server started"
reactor.run()

上面 server.py建立好之后

在终端:sudo python server.py   开启服务器 看到  Iphone Chat server started ,开启成功;

二:终端测试服务器

1:在上面服务器开启成功之后;

2:打开另一个终端:telnet localhost 80 回车,即可看到 socket 连接成功;Connected to localhost.

3: 在终端里面输入测试信息:iam:cc 回车; msg:hi   回车;即可以两个终端下看到实时的信息传递情况;

4:再新建立一个终端:telnet localhost 80 即可实现,多个client 连接 服务器 socket

三:在iOS 端建立 socket 连接 client

1:先建立两个实例变量,并实现代理

@interface ViewController : UIViewController<NSStreamDelegate>

{
NSInputStream *inputStream;
NSOutputStream *outputStream;
} @end

2:建立 socket 与本地 socket 服务器

- (void)initNetworkCommunication
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"localhost", , &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream; [inputStream setDelegate:self];
[outputStream setDelegate:self]; [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [inputStream open];
[outputStream open]; }

3:测试加入聊天和发送聊天

- (void)joinChatServer
{
NSString *name=@"cc";
NSString *response = [NSString stringWithFormat:@"iam:%@",name];
NSData *data = [[NSData alloc]initWithData:[response dataUsingEncoding:NSUTF8StringEncoding]]; [outputStream write:[data bytes] maxLength:[data length]]; } - (void)sendMesage
{
NSString *mess=@"hello world";
NSString *response = [NSString stringWithFormat:@"msg:%@",mess];
NSData *data = [[NSData alloc]initWithData:[response dataUsingEncoding:NSUTF8StringEncoding]]; [outputStream write:[data bytes] maxLength:[data length]];
}

4:在代理中接收socket传递的信息

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {

    switch (streamEvent) {

        case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");
break; case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) { uint8_t buffer[];
int len; while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > ) { NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding]; if (nil != output) {
NSLog(@"server said: %@", output);
}
}
}
}
break; case NSStreamEventErrorOccurred:
NSLog(@"Can not connect to the host!");
break; case NSStreamEventEndEncountered:
break; default:
NSLog(@"Unknown event");
} }

四:参考:

http://www.raywenderlich.com/3932/networking-tutorial-for-ios-how-to-create-a-socket-based-iphone-app-and-server

https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/UsingSocketsandSocketStreams.html

http://www.cnblogs.com/kesalin/archive/2013/04/14/ios_cfnetwork.html

https://developer.apple.com/library/ios/qa/qa1652/_index.html

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html

iOS socket Stream 服务器端 及 客户端 演示的更多相关文章

  1. C#线程池多线程Socket通讯 服务器端和客户端示例

    using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; ...

  2. Java中使用Socket实现服务器端和客户端通讯

    创建服务器端serverSocket import java.io.BufferedReader; import java.io.IOException; import java.io.InputSt ...

  3. Windows10 VS2017 C++ Server Socket简单服务器端与客户端

    服务端: #include "pch.h" #include<iostream> #include<WinSock2.h> #include <Ws2 ...

  4. 计算机网络:套接字(Socket)| Python socket实现服务器端与客户端通信,使用TCP socket阿里云ECS服务器与本机通信

    所谓套接字(Socket),就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象.一个套接字就是网络上进程通信的一端,提供了应用层进程利用网络协议交换数据的机制.从所处的地位来讲,套接字上联应 ...

  5. IOS Socket 04-利用框架CocoaAsyncSocket实现客户端/服务器端

    这篇文章,我们介绍CocoaAsyncSocket框架的使用,主要介绍实现客户端/服务器端代码,相信在网上已经很多这样的文章了,这里做一下自己的总结.这里介绍使用GCD方式 一.客户端 1.下载地址 ...

  6. IOS Socket 05-XMPP开始&安装服务器openfire&安装配置客户端

    1. 即时通讯技术简介(IM) 即时通讯技术(IM-Instant Messageing)支持用户在线实时交谈.如果要发送一条信息,用户需要打开一个小窗口,以便让用户及其朋友在其中输入信息并让交谈双方 ...

  7. Socket(套接字)在服务器端和客户端之间的基本工作原理

    Socket之间的连接过程主要可以概括为以下三步: 服务器建立监听:客户端初始化Socket动态库后创建套接字,然后指定客户端Socket的地址,循环绑定Socket直至成功,然后开始建立监听,此时客 ...

  8. iOS socket 笔记

    ios 客服端: 下载 AsyncSocket 开发框架,拖到项目中 //建立 #import "ViewController.h" #import <sys/socket. ...

  9. IOS Socket 03-建立连接与登录

    1. 搭建python服务器 这里我们用到python服务器Socket Server.如何运行Server?下面介绍 1)通过百度云下载文件 http://pan.baidu.com/s/1i5yb ...

随机推荐

  1. Ubuntu下查看软件版本及安装位置

    查看软件版本: XXX --version 或 aptitude show xxx 也可用apt-show-versions (要先安装sudo apt-get install apt-show-ve ...

  2. 解决Android-studio假死机建议

    背景 终于第一个ios app发布应用商店送审了,这下也有时间把以前写的android更新一版,但是很久没遇到的as假死机问题又各种折腾了一天..最终解决的方法实在是让人忍无可忍,实在是想写下来给那些 ...

  3. bzoj 2724 在线区间众数

    如果不是在线,就是裸的莫队. 但这道题要求在线,然后就不会了.. 标程: http://hi.baidu.com/__vani/item/ecc63f3527395283c2cf2945 算法主要是分 ...

  4. bzoj 1012 BST 支持插入,区间最大

    水... /************************************************************** Problem: 1012 User: idy002 Lang ...

  5. [转]java中Collections.sort排序详解

      Comparator是个接口,可重写compare()及equals()这两个方法,用于比价功能:如果是null的话,就是使用元素的默认顺序,如a,b,c,d,e,f,g,就是a,b,c,d,e, ...

  6. git fetch, git pull 以及 FETCH_HEAD

    git push. 这个很简单, 其实和后面的差不多, 这里就不讲了. 唯一需要注意的地方是: git push origin :branch2, 表示将一个内容为空的同名分支推送到远程的分支.(说白 ...

  7. python - 在Windows系统中安装Pygame及导入Eclipse

    环境:python3.6(只有一个版本)+ windows10(64 bit)  + Eclipse+pydev python3.6安装完成后,会自带 easy_install 和 pip3,在Win ...

  8. Android ButterKnife注解框架使用

    这段时间学习了下ButterKnife注解框架,学习的不是特别深入,但是基础也差不多了,在此记录总结一下. ButterKnife是一个Android View注入的库,主要是注解的使用,可以减少很多 ...

  9. The differentiation program with abstract data

    #!r6rs ( import ( rnrs base ( 6 ) )          ( rnrs io simple ( 6 ) ) ) ( define ( deriv exp var )   ...

  10. windows10使用arcgis注意事项

    平板电脑模式