This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
PSSearching.swift
executable file
·104 lines (90 loc) · 2.93 KB
/
PSSearching.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
//
// PSSearching.swift
// BeamNG.SteeringDevice
//
// Created by Pawel Sulik on 10.10.14.
// Copyright (c) 2014 28Apps. All rights reserved.
//
import Foundation
import UIKit
class PSSearching : NSObject, AsyncUdpSocketDelegate
{
var socket : AsyncUdpSocket!;
var listenSocket : AsyncUdpSocket!;
var onConnectToHost : ((String, UInt16)->(Void))! = nil;
var code : String = "232664";
var initCon : Bool = false;
override init()
{
super.init();
socket = AsyncUdpSocket();
do {
try socket.enableBroadcast(true)
} catch _ {
};
listenSocket = AsyncUdpSocket(delegate: self);
do {
try listenSocket.bind(toPort: 4445)
} catch _ {
};
listenSocket.receive(withTimeout: -1, tag: 0);
}
deinit {
listenSocket.close();
socket.close();
}
convenience init(connectionHandler: @escaping ((String, UInt16)->(Void)))
{
self.init();
self.onConnectToHost = connectionHandler;
}
func broadcast(_ timeout : CFTimeInterval)
{
let message : NSString = "beamng|\(UIDevice.current.name)|\(code)" as NSString;
let data = message.data(using: String.Encoding.utf8.rawValue);
print("Broadcasting from: \(PSNetUtil.localIPAddress())")
socket.send(data, toHost: PSNetUtil.broadcastAddress(), port: 4444, withTimeout: timeout, tag: 0);
}
func onUdpSocket(_ sock: AsyncUdpSocket!, didNotReceiveDataWithTag tag: Int, dueToError error: NSError!)
{
print("PSSearching: didNotReceiveData");
print(error);
}
func onUdpSocket(_ sock: AsyncUdpSocket!, didNotSendDataWithTag tag: Int, dueToError error: NSError!)
{
print("PSSearching: didNotSendData");
}
func onUdpSocket(_ sock: AsyncUdpSocket!, didReceive data: Data!, withTag tag: Int, fromHost host: String!, port: UInt16) -> Bool
{
if (!initCon) {
let msg : NSString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)!;
print("\nPSSearching: Received data!\n\t\(msg)\nfrom: \(host):\(port)");
let temp : NSString = NSString(string: host);
if(temp.contains(PSNetUtil.localIPAddress()))
{
print("Received own data!");
return false;
}
if(msg as String == "beamng|\(code)")
{
//print("Recieved Message...");
if(onConnectToHost != nil)
{
//print(host);
initCon = true;
onConnectToHost(host, 4445);
}
print("Connecting people...");
}
listenSocket.receive(withTimeout: -1, tag: 0);
return true;
}
return false;
}
func onUdpSocket(_ sock: AsyncUdpSocket!, didSendDataWithTag tag: Int)
{
}
func onUdpSocketDidClose(_ sock: AsyncUdpSocket!)
{
}
}