Skip to content

Instantly share code, notes, and snippets.

@menangen
Last active September 6, 2018 14:18
Show Gist options
  • Save menangen/d65679018bc48138e92aa6857e0ae22c to your computer and use it in GitHub Desktop.
Save menangen/d65679018bc48138e92aa6857e0ae22c to your computer and use it in GitHub Desktop.
Apple Network Framework. Swift UDP hello world
import socket
UDP_IP = "192.168.1.5"
UDP_PORT = 5000
MESSAGE = b"Hello, World!"
print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)
print("message:", MESSAGE)
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
import socket
class UDPServer:
UDP_IP = "192.168.1.5"
UDP_PORT = 5000
def __init__(self, ip: str = UDP_IP, port: int = UDP_PORT):
self.udpSocket = socket.socket(
socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
self.udpSocket.bind((ip, port))
print("Serving on", ip, port)
self.counterPacket = 1
while True:
try:
data, addr = self.udpSocket.recvfrom(1024) # buffer size is 1024 bytes
print("Received message:", data, "from", addr)
self.process(data, addr)
except KeyboardInterrupt:
print("\tClosed by an Interrupt")
break
def process(self, data: bytes, from_addr):
print("Processing data:", data)
if data == b"getLast":
print("sending Counter = {}".format(self.counterPacket))
self.udpSocket.sendto(bytes(self.counterPacket), from_addr)
print("Sent... to", from_addr[0])
self.counterPacket += 1
UDPServer()
//
// UDPClient.swift
// NetworkUDP
//
// Created by menangen on 31.08.2018.
//
//
import Foundation
import Network
class UDPClient {
var connection: NWConnection
var queue: DispatchQueue
init() {
queue = DispatchQueue(label: "UDP Client Queue")
let host = NWEndpoint.Host.ipv4(IPv4Address("192.168.1.5")!)
let port = NWEndpoint.Port(rawValue: 5000)!
connection = NWConnection(to: .hostPort(host: host, port: port), using: .udp)
connection.stateUpdateHandler = { (newState) in
switch (newState) {
case .ready:
print("Ready to send")
case .failed(let e):
print("Client failed with error \(e)")
default:
break
}
}
connection.start(queue: queue)
}
func send(_ number: UInt16) {
let message = number == 0 ? "getLast" : String(number)
connection.send(content: message.data(using: .ascii), completion: .contentProcessed({
(error) in
if let error = error {
print("Send error: \(error)")
}
})
)
connection.receive(minimumIncompleteLength: 4, maximumLength: 1024, completion: {
(data, context, isComplete, error) in
if data != nil {
print("Received!", data ?? "Empty content")
}
})
print("Sent...")
}
}
//
// ViewController.swift
// NetworkUDP
//
// Created by menangen on 29.08.2018.
//
import UIKit
class ViewController: UIViewController {
let client: UDPClient
required init?(coder aDecoder: NSCoder) {
print("init coder style")
self.client = UDPClient()
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black
}
@IBAction func pressed() {
print("Sending")
self.client.send(0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment