最近用wcf 服務 給ios和安卓做接口,做了幾個ios的項目 用udp 組播 讓ios多終端接收和刷新方法
做一個簡單的小例子會把工程給大家下載的
c#代碼:netSocketUDP.rar
ios代碼:MyIOSSocketDemo.rar
先用c#做發送
組播IP范圍為 224.0.0.0~239.255.255.255
建一個控制台應用程序
private static IPAddress GropuAddress = IPAddress.Parse("224.0.0.2");//IP
private static int GrupPort = 12001;//端口
static void Main(string[] args)
{
for (int i = 0; i < 1000; i++)
{
System.Threading.Thread.Sleep(3000);//等待3秒再發
Send("sendMessage"+i.ToString()+"個!");
}
}
public static void Send(string message)
{
//不在一個網段也可以收到
Socket server = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 12002);
IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("224.0.0.2"), 12001);
server.Bind(iep);
byte[] data = Encoding.ASCII.GetBytes(message);
server.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
new MulticastOption(IPAddress.Parse("224.100.0.1")));
server.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.MulticastTimeToLive, 50);
server.SendTo(data, iep2);
server.Close();
}
順便把c#接收也說一下(這個可以不用看,因為我們要做的是ios接收)
static void Main(string[] args)
{
StartListener();
Console.ReadLine();
}
private static void StartListener()
{
byte[] b = new byte[10240];
try
{
while (true)
{
System.Threading.Thread.Sleep(500);
String multiAddress = "224.0.0.2";//Datagrams.getMultiIPAddress("192.168.2.106");
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 12001);
s.Bind(ipep);
IPAddress ip = IPAddress.Parse(multiAddress);
s.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.AddMembership,
new MulticastOption(ip, IPAddress.Any));
s.ReceiveTimeout = 5000;
s.Receive(b);
string sss = System.Text.Encoding.UTF8.GetString(b).Replace("\0", "").Trim();
Console.WriteLine(sss);
s.Close();
}
}
catch (Exception ex)
{
Console.WriteLine("receive multicast exception:" + ex.ToString());
}
}
ios接收
ios 用到的一個類庫AsyncUdpSocket 這個類庫就是發送和接收收 組播的 用起來很方便網上有好多例子我就簡單說一下
建一個Single View Application
把AsyncUdpSocket.h 和AsyncUdpSocket.m加到工程里
窗體上放一個文本顯示收到的信息
在ViewController.h里加入
#import "AsyncUdpSocket.h"
@interface ViewController : UIViewController<AsyncUdpSocketDelegate>
@property (strong, nonatomic) IBOutlet UITextField *MyResaveTxt;//頁面上的文本 @property (nonatomic,strong) AsyncUdpSocket *udpSocket; -(void)openUDPServer;
在ViewController.m 里實現
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize udpSocket,MyResaveTxt;
- (void)viewDidLoad
{
[super viewDidLoad];
[self openUDPServer];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void) openUDPServer
{
//初始化udp
AsyncUdpSocket *tempSocket=[[AsyncUdpSocket alloc] initWithDelegate:self];
self.udpSocket=tempSocket;
//綁定端口
NSError *error = nil;
[self.udpSocket bindToPort:12001 error:&error];
//發送廣播設置
[self.udpSocket enableBroadcast:YES error:&error];
//加入群里,能接收到群里其他客戶端的消息
[self.udpSocket joinMulticastGroup:@"224.0.0.2" error:&error];
//啟動接收線程
[self.udpSocket receiveWithTimeout:-1 tag:0];
}
//接收
-(BOOL) onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port
{
NSString * info=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
MyResaveTxt.text=info;
[self.udpSocket receiveWithTimeout:-1 tag:0];//啟動接收線程
return YES;
}
@end
c#代碼:netSocketUDP.rar
ios代碼:MyIOSSocketDemo.rar
補一下發漢字會有亂碼
c#用
byte[] data =System.Text.Encoding.Default.GetBytes(message);
ios用
NSStringEncoding strEncode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString * info=[[NSString alloc] initWithData:data encoding:strEncode ];
ios URL中文轉碼
方法1
NSString *url =@"www.haha.com/這是中文";
NSStringEncoding chineseEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
url = [url stringByAddingPercentEscapesUsingEncoding:chineseEncoding];
NSLog(@"%@",url);
NSMutableURLRequest *request = [[NSMutableURLRequestalloc] init];
// 設置URL
[request setURL:[NSURL URLWithString:url]];
// 設置HTTP方法
[request setHTTPMethod:@"GET"];
// 發送同步請求, 這里得returnData就是返回得數據
NSData *data = [NSURLConnectionsendSynchronousRequest:request
returningResponse:nil error:nil];
方法2
- (NSString *)URLEncodedString
{
NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)self,NULL,CFSTR("!*'();:@&=+$,/?%#[]"),kCFStringEncodingUTF8);
[result autorelease];
return result;
}
