美好的一天,
我正在制作一个Android应用程序,它将UDP数据包发送到Ruby服务器,然后将它们转发给所有订阅的Android客户端,包括原始发件人。
我的服务器接收数据包,但无法通过UDP套接字发送或连接。
服务器代码片段(Ruby,在Fedora 22上):
//
// ChooseShopViewController.swift
// MirrorMirror
//
// Created by Ben on 12/09/15.
// Copyright (c) 2015 Amber. All rights reserved.
//
import UIKit
import Parse
class ChooseShopViewController: UIViewController {
var progressView: UIProgressView?
private var allProducts: [Product] = []
private var categories: [ProductCategory] = []
@IBAction func loadProducts(sender: AnyObject) {
let shopQuery = PFQuery(className:"Shop")
shopQuery.getObjectInBackgroundWithId("QjSbyC6k5C") {
(glamour: PFObject?, error: NSError?) -> Void in
if error == nil && glamour != nil {
let query = PFQuery(className:"Product")
query.whereKey("shopId", equalTo: glamour!)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
self.getAllProductsAndCategories(objects, error: error)
}
} else {
print(error)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Create Progress View Control
progressView = UIProgressView( progressViewStyle:
UIProgressViewStyle.Default)
progressView?.center = self.view.center
view.addSubview(progressView!)
}
override func prepareForSegue( segue: UIStoryboardSegue,
sender: AnyObject?) {
if (segue.identifier == "dressingRoom") {
ShopDisplay.sharedInstance.setAllProducts(self.allProducts)
ShopDisplay.sharedInstance.setAllProductCategories(self.categories)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func getAllProductsAndCategories(objects: [AnyObject]?, error: NSError?) {
if error == nil {
if let objects = objects as? [PFObject] {
for product in objects {
self.getCategory(product)
self.getProduct(product)
}
}
} else {
print("Error: \(error!) \(error!.userInfo)")
}
}
func getCategory(product: PFObject) {
if let category = product["category"] as? String {
var alreadyThere: Bool = false
for item in self.categories {
if category == item.rawValue {
alreadyThere = true
break
}
}
if alreadyThere == false {
self.categories.append(ProductCategory(rawValue: category)!)
}
}
}
func getProduct(product: PFObject) {
if let productImage = product["imageFile"] as? PFFile {
productImage.getDataInBackgroundWithBlock ({
(imageData: NSData?, error: NSError?) -> Void in
if let imageData = imageData {
let image = UIImage(data:imageData)
self.allProducts.append(
Product(object: product, image: image!))
}
if let downloadError = error {
print(downloadError.localizedDescription)
}
}, progressBlock: {
(percentDone: Int32) -> Void in
self.progressView?.progress = Float(percentDone)
if (percentDone == 100) {
//self.performSegueWithIdentifier("dressingRoom", sender: UIColor.greenColor())
}
})
}
}
}
客户端代码段:
SERVER_SEND_PORT = 4000
ANDROID_PORT = 7500
# Send socket
s_socket = UDPSocket.new
s_socket.setsockopt(Socket::SOL_SOCKET,Socket::SO_BROADCAST, 1)
s_socket.bind(SERVER_IP, SERVER_SEND_PORT)
# Receive socket
r_socket = UDPSocket.new
r_socket.setsockopt(Socket::SOL_SOCKET,Socket::SO_BROADCAST, 1)
r_socket.bind(SERVER_IP, RECEIVE_PORT)
$clientIPs = []
$clientPorts = []
def broadcast(data)
$clientIPs.each_with_index do |ip, index|
puts "trying to send #{data}"
s_socket.connect(ip, ANDROID_PORT) # does not pass this step
puts "connected"
s_socket.send(data, 0)
#s_socket.send(data, 0, ip, ANDROID_PORT)
puts "sent: " + data;
end
end
while true
data, client = r_socket.recvfrom(256)
puts "received: " + data
Thread.new(client) do |clientAddr|
if !$clientIPs.include? clientAddr[3]
$clientIPs << clientAddr[3]
$clientPorts << clientAddr[1]
end
broadcast(data)
end
end
private static final int LISTENING_PORT = 7500;
public void onStart() {
/* Unrelated code + Sending socket */
// Receiving Thread
new Thread(){
public void run() {
// Create receiving socket at a given port
try {
rSocket = new DatagramSocket(LISTENING_PORT);
rSocket.setBroadcast(true);
} catch (SocketException e) {
e.printStackTrace();
}
Log.d("Trace", "Created receiving socket");
while (true) {
if (rSocket != null) {
// Receive data
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
try {
rSocket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Got the packet!");
}
}
}
}.start();
}
未在服务器中显示任何UDP连接。