Study
Network.framework Study: Server side
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