[JAVA] Étude Swift Network.framework 2019 1207 «Serveur UDP»

Study

Network.framework Etude: côté serveur

environnement

Client:Java、NetBeans Server:Swift、Xcode

Client Source Java

package example.java.network;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class ExampleClientUDP {
    public static void main(String[] args) {
        String sendData = "Send Data Example";
        try {
            DatagramSocket datagramSocket = new DatagramSocket();
            DatagramPacket datagramPacke = new DatagramPacket(sendData.getBytes(), sendData.getBytes().length, InetAddress.getByName("localhost"), 7777);
            datagramSocket.send(datagramPacke);
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}

Server Source Swift

Utiliser NWLister Passez simplement de la version TCP à ".udp".

main.swift

import Foundation
import Network

var networkServer = NetworkServer()

networkServer.startListener()

while networkServer.running {
    sleep(1)
}

NetworkServer.swift

import Foundation
import Network

class NetworkServer {
    public var running = true

    func startListener() {
        let myQueue = DispatchQueue(label: "ExampleNetwork")

        do {
            let nWListener = try NWListener(using: .udp, on: 7777)
            nWListener.newConnectionHandler = { (newConnection) in
                print("New Connection!!")
                newConnection.start(queue: myQueue)
                self.receive(nWConnection: newConnection)
            }
            nWListener.start(queue: myQueue)
            print("start")
        }
        catch {
            print(error)
        }
    }
    
    func receive(nWConnection:NWConnection) {
        nWConnection.receive(minimumIncompleteLength: 1, maximumLength: 5, completion: { (data, context, flag, error) in
            print("receiveMessage")
            if let data = data {
                let receiveData = [UInt8](data)
                print(receiveData)
                print(flag)
                if(flag == false) {
                    self.receive(nWConnection: nWConnection)
                }
            }
            else {
                print("receiveMessage data nil")
            }
        })
    }
    
}

Recommended Posts

Étude Swift Network.framework 2019 1207 «Serveur UDP»
Étude Swift Network.framework 2019 1204 «UDP»
Étude Swift Network.framework 2019 1205 «Serveur TCP»
Étude Swift Network.framework 20191203
Étude Swift Network.framework 2019 1210 "Bonjour Parcourir"
Étude Swift Network.framework 2019 1206 «Serveur TCP» Partie 2 Utiliser la méthode de réception
Étude Swift Network.framework 2019 1208 «Envoyer et recevoir»
Etude Swift Network.framework 20200319 "Recevoir et envoyer"
Swift Network.framework Study 2019 1207 «Server TCP» Partie 3 Amélioration de l'utilisation de la méthode de réception