ios 接收 c# socket udp 组播

简介:

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

    NSMutableURLRequest *request = [[NSMutableURLRequestallocinit];

            // 设置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;
 
}

  本文转自lpxxn博客园博客,原文链接:http://www.cnblogs.com/li-peng/archive/2012/11/21/2780647.html,如需转载请自行联系原作者

相关文章
|
6月前
14.5 Socket 应用组播通信
组播通信是一种基于UDP协议的网络通信方式,它允许发送方将消息同时传递给多个接收方。在组播通信中,发送方和接收方都会加入一个共同的组播组,这个组播组对应一个特定的IP地址,所有加入该组播组的主机都能够接收到发送方发送的消息。组播通信可以有效地减少网络流量和网络负载,因为在传统的点对点通信方式下,每个消息都需要单独传输到每个接收方,而在组播通信中,每个消息只需要传输一次,就可以同时传递给多个接收方。在使用组播模式时,需要在套接字上使用`setsockopt()`函数来设置套接字的`IP_MULTICAST_IF`选项,指定本地主机的出站接口地址,用于发送组播数据包。此外,还可以设置`IP_ADD
58 0
14.5 Socket 应用组播通信
|
8月前
|
网络协议 Linux C语言
linux下CC++网络编程基本:socket实现tcp和udp的例子
linux下CC++网络编程基本:socket实现tcp和udp的例子
161 0
|
6月前
|
安全 网络协议 Java
Thread类的用法 && 线程安全 && 多线程代码案例 && 文件操作和 IO && 网络原理初识 &&UDP socket
Thread类的用法 && 线程安全 && 多线程代码案例 && 文件操作和 IO && 网络原理初识 &&UDP socket
38 0
|
1月前
|
网络协议 Linux
TCP 和 UDP 的 Socket 调用
【2月更文挑战第19天】
TCP 和 UDP 的 Socket 调用
|
4月前
|
存储 网络协议 安全
网络编程『socket套接字 ‖ 简易UDP网络程序』
网络编程『socket套接字 ‖ 简易UDP网络程序』
75 0
|
4月前
|
网络协议
百度搜索:蓝易云【基于TCP/UDP的Socket编程】
通过使用上述示例,您可以基于TCP或UDP协议进行Socket编程,实现网络通信功能。根据您的需求,可以进一步扩展和定制这些示例代码。
36 1
|
3月前
|
网络协议
百度搜索:蓝易云【基于TCP/UDP的Socket编程。】
以上是基于TCP/UDP的Socket编程的基本步骤和函数调用。通过理解和掌握这些概念和操作,可以实现网络应用程序的数据传输和通信功能。
47 1
|
6月前
|
域名解析 存储 移动开发
TCP socket && UDP && TCP协议 && IP协议 && 以太网等
TCP socket && UDP && TCP协议 && IP协议 && 以太网等
36 0
|
6月前
|
存储 网络协议 Java
网络编程:UDP socket
网络编程:UDP socket
52 0
|
7月前
|
网络协议 安全
基于TCP和UDP的Socket通信
TCP是面向连接的,安全的协议,它是一对一的关系 udp是面向无连接的,不安全,不可靠的,但是效率很高,支持一对一,一对多,多对多发送,udp传输的格式为数据报,要将其封装为数据报才能发送,
49 1