Swift Network.framework Study 20200319「Receive and Send」
Study
Network.framework
Study:Receive and Send
環境
Client:Java、NetBeans
Server:Swift、Xcode
Server Source Swift
main.swift
1 2 3 4 5 6 7 8 | import Foundation import Network var receiveANdSend = ReceiveAndSend () receiveANdSend . startListener () while receiveANdSend . running { sleep ( 1 ) } |
ReceiveAndSend.swift
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | import Foundation import Network class ReceiveAndSend { public var running = true func startListener () { let myQueue = DispatchQueue ( label : "ExampleNetwork" ) do { let nWListener = try NWListener ( using : . tcp , 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 ) self . sendMessage ( nWConnection ) if ( flag == false ) { self . receive ( nWConnection : nWConnection ) } } else { print ( "receiveMessage data nil" ) } }) } func sendMessage ( _ connection : NWConnection ) { let data = "Answer" . data ( using : . utf8 ) let completion = NWConnection . SendCompletion . contentProcessed { ( error : NWError ?) in print ( "応答送信完了" ) self . running = false } connection . send ( content : data , completion : completion ) } } |
Client Source Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public class ExampleSendAndReceive { public static void main(String[] args) { try (Socket socket = new Socket( "localhost" , 7777 ); PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true );) { Runnable runnable = () -> { System.out.println( "Receive start" ); try { int data = socket.getInputStream().read(); while (data != - 1 ) { System.out.print(data + " " ); data = socket.getInputStream().read(); } System.out.println( "end" ); } catch (Exception e) { System.out.println(e); } }; Thread thread = new Thread(runnable); thread.start(); for ( int i = 0 ; i < 5 ; i++) { printWriter.println( "12345" ); Thread.sleep( 5000 ); } } catch (Exception e) { System.out.println(e); } } } |