最近用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;
}