[JAVA] Swift Network.framework Study 2019 1207 "Server UDP"

Study

Network.framework Study: Server side

environment

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

Use NWLister Just change from the tcp version to ".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

Swift Network.framework Study 2019 1207 "Server UDP"
Swift Network.framework Study 2019 1204 "UDP"
Swift Network.framework Study 2019 1205 "Server TCP"
Swift Network.framework Study 20191203
Swift Network.framework Study 2019 1210 "Bonjour Browse"
Swift Network.framework Study 2019 1206 "Server TCP" Part 2 Use receive method
Swift Network.framework Study 2019 1208 "Send and Receive"
Swift Network.framework Study 20200319 "Receive and Send"
Swift Network.framework Study 2019 1207 "Server TCP" Part 3 Use of receive method Improvement