Итак, у меня есть этот код Java (Android), который использует DatagramPacket для отправки и получения сообщений UDP.
DatagramSocket ds = null;
ds = new DatagramSocket();
ds.setSoTimeout(30000);
InetAddress serverAddr = InetAddress.getByName(IP_ADDRESS);
DatagramPacket dp;
dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), serverAddr, UDP_SERVER_PORT);
ds.send(dp);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
ds.receive(receivePacket);
response = new String(receivePacket.getData(), "UTF-8");
String str = new String(receivePacket.getData(), "UTF-8");
data1 = str.substring(0,receivePacket.getLength());
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String sender = intent.getStringExtra("sender");
Bundle msg = intent.getBundleExtra("message");
}
};
LocalBroadcastManager.getInstance(context).registerReceiver(
mMessageReceiver, new IntentFilter("UDPBroadcast"));
Теперь я хочу сделать то же самое на iOS.В настоящее время у меня есть этот код.
let manager = SocketManager(socketURL: URL(string: "http://\(host):\(connectPort)")!, config: [.log(true), .compress])
let socket = manager.defaultSocket
socket.on(clientEvent: .connect) {data, ack in
print("socket connected")
}
socket.on("sender") {data, ack in
print("sender data: \(data)")
}
socket.connect()
Но он дает мне эти журналы
SocketIOClient{/}: Adding handler for event: connect
SocketIOClient{/}: Adding handler for event: sender
SocketIOClient{/}: Handling event: statusChange with data: [connecting]
SocketIOClient{/}: Joining namespace /
SocketManager: Tried connecting socket when engine isn't open. Connecting
SocketManager: Adding engine
SocketManager: Manager is being released
SocketIOClient{/}: Client is being released
SocketEngine: Starting engine. Server: http://255.255.255.255:6000
SocketEngine: Handshaking
SocketEnginePolling: Doing polling GET http://255.255.255.255:6000/socket.io/?transport=polling&b64=1
SocketEnginePolling: Could not connect to the server.
SocketEngine: Could not connect to the server.
SocketEngine: Engine is being released
Сервер, которому я звоню, является сервером golang и самоподписан.Код Android выполняется быстро.Я новичок в разработке iOS и сокетов.Если вы могли бы порекомендовать другие модули, которые могут подключаться к сокету, кроме SocketIO, пожалуйста, включите образец кода или ссылку на него.
ОБНОВЛЕНИЕ: Это мой текущий код
import Foundation
import CocoaAsyncSocket
import SocketIO
import Starscream
class UDPSocket: NSObject, GCDAsyncUdpSocketDelegate{
var udpSock : GCDAsyncUdpSocket!
let listenPort: UInt16 = 6000
let data = "test".data(using: String.Encoding.utf8)!
let host = "255.255.255.255"
let connectPort: UInt16 = 6000
let manager = SocketManager(socketURL: URL(string: "http://255.255.255.255:6000")!, config: [.log(true), .compress])
override init() {
super.init()
print("init")
udpSock = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.main)
do{
try udpSock!.bind(toPort: listenPort)
try udpSock!.enableBroadcast(true)
}catch _ as NSError {
print("Issue with d to Port")
return
}
let socket = manager.defaultSocket
socket.on(clientEvent: .connect) {data, ack in
print("socket connected")
}
socket.on("sender") {data, ack in
print("sender data: \(data)")
}
socket.connect()
}
func sendUDP(){
do {
try udpSock!.beginReceiving()
udpSock.send(data, toHost: host, port: connectPort, withTimeout: 60, tag: 0)
}catch _ as NSError {
print("Issue with sending to Port: ")
return
}
}
public func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) {
let str = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue)
print("received: \(String(describing: str))")
if let data1 = str?.intValue{
if(data1 > 0){
print("data1 isNum: \(data1)")
}
}
}
public func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) {
print("didSendDataWithTag")
}
public func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) {
print("didNOTSendDataWithTag err: \(String(describing: error))")
}
public func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) {
print("didNOTConnect")
}
public func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) {
print("DidCloseSocket")
}
@objc public func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data) {
let str = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue)
print("didConnectToAddress addr: \(String(describing: str))")
}
}