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

Study Network.framework Etude: côté client

environnement

Client:Swift、Xcode Server:Java、NetBeans

Client Source Swift

Swift définit simplement "NWParameters.udp" dans NWConnection.

import Foundation
import Network

var running = true

func startConnection() {
    let myQueue = DispatchQueue(label: "ExampleNetwork")
    let connection = NWConnection(host: "localhost", port: 7777, using: NWParameters.udp)
    connection.stateUpdateHandler = { (newState) in
        switch(newState) {
        case .ready:
            print("ready")
            sendMessage(connection)
        case .waiting(let error):
            print("waiting")
            print(error)
        case .failed(let error):
            print("failed")
            print(error)
        default:
            print("defaults")
            break
        }
    }
    connection.start(queue: myQueue)
}

func sendMessage(_ connection: NWConnection) {
    let data = "Example Send Data".data(using: .utf8)
    let completion = NWConnection.SendCompletion.contentProcessed { (error: NWError?) in
        print("envoyer complètement")
        running = false
    }
    connection.send(content: data, completion: completion)
}

startConnection()

//dispatchMain()

while running {
    sleep(1)
}

Server Source Java Java utilise différentes classes pour TCP et UDP.

package example.java.network;

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

public class ExampleServerUDP {
    private static final int EXHOMAX = 255;
    
    public static void main(String[] args) {
        try {
            DatagramSocket​ datagramSocket = new DatagramSocket​(7777);
            DatagramPacket datagramPacket = new DatagramPacket(new byte[EXHOMAX], EXHOMAX);
            while(true) {
                datagramSocket.receive(datagramPacket);
                for(int i = 0; i < datagramPacket.getLength(); i++) {
                    System.out.print(datagramPacket.getData()[i]);
                    System.out.print(" ");
                }
                System.out.println();
                datagramPacket.setLength(EXHOMAX);
            }
        }
        catch(Exception e) {
        }
    }
}

Recommended Posts

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