发送“Hello World"从 iPhone 通过 udp 发送消息发送消息、World、Hello、quot

2023-09-07 13:20:54 作者:放肆的我の蓝天

我是目标 C 的新手,我需要通过 UDP 发送一条简单的消息.服务器部分正在工作,因为它是用 C# 实现的.

I am new to objective C and I need to send a simple message via UDP. The server part is working cause it is implemented in C#.

C#中的服务器代码是:

The server code in C# is:

 var server = new UdpClient(8585);
 var groupEP = new IPEndPoint(IPAddress.Parse("192.168.0.120"),8585);
 byte[] bytes = server.Receive(ref groupEP);

而c#中的客户端部分是:

and the client part in c# is:

   System.Net.Sockets.UdpClient client;     
client = new System.Net.Sockets.UdpClient("192.168.0.120",8585);    
client.Send(new byte[]{1,2,3,4},4);

如何在目标 c 中执行相同的客户端部分?我知道互联网上有很多教程,例如 this library.当我将该库导入我的项目时,我不知道如何实例化一个新对象.我试过了:

how can I do the same client part in objective c? I know there are a lot of tutorials on the internet such as this library. when I import that library to my project I do not know how to instantiate a new object. I have tried:

 [[GCDAsyncUdpSocket alloc] initWithSocketQueue:... ??? I don't know how to initialize it.

如果有人可以向我展示一个简单的示例,说明如何将客户端部分复制到目标 c 中,我将不胜感激.

I will appreciate if someone can show me a simple example of how could I replicate the client part into objective c.

推荐答案

从这里.那么您可以将数据包发送为:

download GCDAsyncUdpSocket from here. then you may send packets as:

 GCDAsyncUdpSocket *udpSocket ; // create this first part as a global variable
 udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

 NSData *data = [ 
                   [NSString stringWithFormat:@"%Hello Wold" 
                    dataUsingEncoding:NSUTF8StringEncoding
                ];

[udpSocket sendData:data toHost:@"192.168.10.111" port:550 withTimeout:-1 tag:1];