Swift Network.framework Study 20191203

Study

Network.framework Study: Client side

environment

Client:Swift、Xcode Server:Java、NetBeans

Client Source Swift

import Foundation
import Network

func startConnection() {
    let myQueue = DispatchQueue(label: "ExampleNetwork")
    let connection = NWConnection(host: "localhost", port: 7777, using: NWParameters.tcp)
    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("send completely")
    }
    connection.send(content: data, completion: completion)
}

startConnection()

while true {
    sleep(1)
}

The last loop is awkward.

Server Source Java

package example.java.network;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ExampleServerSocket {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(7777);
            System.out.println("socket create");
            Socket socket = serverSocket.accept();
            System.out.println("accept");
            Scanner scanner = new Scanner(socket.getInputStream());
            while(scanner.hasNext() == true) {
                System.out.println(scanner.nextLine());
            }
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}

I forgot the Scanner hasNext () condition after a long time. I have to check and improve.

Recommended Posts

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