DatagramSocket

Hi I'm trying to build a simple test app using DatagramSocket (AIR 2) and I'm wondering if I absolutely need to use a server in order to communication with other applications on the local network. I have a simple test where I have 2 air apps on my home network, app "A" and app "B" (wireless connected laptop and desktop). I have an animation in app A and app B that are identical. I want the animation in app A to sync with app B, so I want app A to tell app B what frame it's currently on, and app B should update it's frame number accordingly. I'm am pretty new to using DatagramSocket, and I'm not even sure that it's the best thing to use. I just figure UDP would be a lot faster than using TCP in the case where there are a lot of things moving on the screen.
If anybody can point to examples of sending UDP over a local network that would be great, or post some code, give insights etc.
Thanks.

I don't understand what the problem is now.The problem is that 1st time when Timeout occurs it throws exception. In catch block i caught the exception and call some function to perform some task. up to here every thing is fine but problem comes when loop iterates for 2nd time* the socket hangs and doesn't throw any exception when Timeout occurs. I m not sure whether Timeout occurs or not. Here is some piece of code.
Some Code Here......
try {
      mnSocket = new DatagramSocket(PORT);
      mnSocket.setSoTimeout(10 * 1000);
      mnSocket.setSendBufferSize(bufferSize);
      mnSocket.setReceiveBufferSize(bufferSize);
      mnSocket.setSoTimeout(10 * 1000);
      sendSolic = new SenderThread(mnSocket, 2);
      solicPacket = new DatagramPacket(buffer, buffer.length);
      while (true) {
        try {
          mnSocket.receive(solicPacket);
          Some Code Here...........
        catch (SocketTimeoutException ste) {
          sendSolic.start();
        Some Code Here........
    catch (SocketException se) {
      se.printStackTrace();
    catch (IOException ioe) {
      ioe.printStackTrace();
   Some Code Here........

Similar Messages

  • How to handle multiple clients with DatagramSocket

    I am trying to handle multiple clients with 1 datagramSocket bind to one port (basically I have only one port to use, and I can not use TCP or any other ports). At the server side I have two threads one for receiving packets and buffering them, another for processing the packets in the buffer and sending replies.
    I can have multiple clients sending datagramPackets to me and I will have to process the packets and send them to DIFFERENT clients. Ex. Client 1 sends datagramPacket to Server which sends the processed packet to Client 2. Also Client 2 sends a datagramPacket to Server which again processes the packet and sends it to Client1. May have Client 3 and 4 doing the same thing at the same time... and so on...
    My root class is creating the datagramSocket(somePort) and two threads (receiver and sender). How can I use the socket that I created in these two threads??
    I have done the following and I am getting "java.net.bindexception". When I am sending stuff from Client1 to Client2 everything is fine but when I start sending something from Client2 to Client 1, I get the bindexception... Client 1 is using port 3000, Client 2 is using port 4000.
    I really don't have a lot of experience in socket programming so I am not sure if there is a much simpler way to do this. I appreciate all the tips and help that I can get...
    Thanks...
    class UDP_serv
         static DatagramSocket udpSocket;
         final static int SERVER_PORT     = 2000;
         public static void main(String[] args) throws SocketException
              udpSocket= new DatagramSocket(SERVER_PORT);
              new DataReceiver().start ();
              new DataSender().start ();
         static class DataReceiver extends Thread
              DataReceiver()
                   Thread.currentThread().setName("DataReceiver");
              public void run()
                   while (true)
                        byte pckt[] = new byte [MaxMsgSize];          
                        DatagramPacket dp = new DatagramPacket (pckt, pckt.length);
                        try
                             udpSocket.receive (dp);
                             //PUSH TO RECEIVE BUFFER
                        catch(Exception e)
                             e.printStackTrace();
         static class DataSender extends Thread
              DataSender()
                   Thread.currentThread().setName("DataSender");
              public void run()
                   while (true)
                        processDataMsg();
          static void processDataMsg() 
             DatagramPacket op;
             InetAddress DA = null;
             int DP = 0;
             byte [] outPacket = null;
             // POP FROM RECEIVE BUFFER
             // SOME PROCESSING HERE     
             // Set Destination Address (DA)
             // Set Destination Port (DP)
             // DA and DP are the forwarding IP and Port addresses
             // not the addresses original packet was sent from.
             try
              op = new DatagramPacket (outPacket, outPacket.length,DA, DP);
              udpSocket.send(op);
             catch (IOException e)
              e.printStackTrace();
    }Also for development and testing purposes, I am running the two clients and the server on the same machine (windows xp-32b) so all of the Destination IP Addresses are 127.0.0.1. and as I said Ports that I am using are 2000, 3000, 4000 (Server, Client1, Client2).

    Hmm I have minimized the code and it seems to be working now.
    I think I have an error in the header portion of the data I am sending, where I am storing the source IP/Port and destination IP/Port. I think the server in the middle is messing these values up while sending them to the destination Client. Because the destination client actually receives the stuff and sends the reply back to the server, but the reply packet's headers has 0/0 as the dest IP / Port...
    Server is giving me java.net.BindException: Cannot assign requested address error when it tries to forward the reply it received from the client2 as the address it is trying to send is 0!
    I guess it doesnt just give this error when you try to open two sockets to the same port...
    Paul, Thanks for the direction on how to proceed... took me a while get the minimized code but at least figured out the problem. Well still have to make sure that is THE problem though :)
    As far as the statics goes how can I change those to non static ones? Where do I make an instance of the top level class that creates the threads? and how do I pass the DatagramSocket to the threads/ if I dont need to pass how do I call or use the datagramSocket I created in the top level class? I mean do I still kinda have it like a global variable on the top?? A very simple example would be much appreciated...
    I think these might be really basic questions but I am having a rough time with the hierarchy in java...

  • DatagramSocket not picking up UDP broadcasts

    Hi All.
    Opened a DatagramSocket on specific port. Verfied (w/ tcpdump) that other process is sending UDP packets to that port with broadcast address (128.0.3.255). {pseudocode}DatagramSocket.recieve(dgram) never picks up the packets.
    If I change the sender to use specific IP (unicast), the recieve gets the packet and unblocks.
    JRE1_5
    Any ideas?
    -K

    Are you binding the socket to the wildcard address?
    Is that really your broadcast address? The 128.0.0.0/16 address block is slightly unusual (RFC 3330). broadcast = ip_address | ~netmask; (or use 255.255.255.255).
    Try these programs; do they work for you? If they do, what is different between these and your program:
    import java.io.*;
    import java.net.*;
    public class BroadcastSend
        public static void main(String args[])
         throws Exception
         DatagramSocket socket = new DatagramSocket();
         socket.setBroadcast(true);
         socket.setReceiveBufferSize(64 * 1024);
         socket.setSendBufferSize(64 * 1024);
         int str_size = args.length == 0 ? 256 : Integer.parseInt(args[0]);
         StringBuffer str = new StringBuffer();
         while (str.length() < str_size)
             str.append("hello world");
         str.setLength(str_size);
         byte buf[] = str.toString().getBytes("ISO-8859-1");
         InetAddress address = InetAddress.getByName("255.255.255.255");
         DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 6666);
         socket.send(packet);
    import java.io.*;
    import java.net.*;
    public class BroadcastReceive
        public static void main(String args[])
         throws Exception
         DatagramSocket socket = new DatagramSocket(6666);
         socket.setBroadcast(true);
         socket.setReceiveBufferSize(64 * 1024);
         socket.setSendBufferSize(64 * 1024);
         while (true) {
             byte buf[] = new byte[64 * 1024];
             DatagramPacket packet = new DatagramPacket(buf, buf.length);
             socket.receive(packet);
             System.out.println("got " + packet.getLength() +
                          " bytes from " + packet.getAddress());
    }

  • DatagramSocket problem when using IPV6

    Hello,
    I've got an odd problem. I have to adapt a program to work with IPV6. The code below exemplifies my problem:
    public static void main(String[] args) {
         try {
            String serverHostname = new String ("fd22::1");
            Inet6Address inetd6 = (Inet6Address)InetAddress.getByName(serverHostname);
            Inet6Address inet6 = (Inet6Address)InetAddress.getByName(new String("fd22::3"));
            DatagramSocket clientSocket = new DatagramSocket(5080, inet6);
            byte[] msg = new byte[1025];
            DatagramPacket dp = new DatagramPacket(msg,msg.length,inetd6,7000);
            clientSocket.send(dp);
            clientSocket.close();
        } catch ( IOException ex ) {
        ex.printStackTrace();
    }When I send messages with more than 1024 bytes to a machine that does not exist in my network ( fd22::1 is not valid ). I get the following output:
    java.net.SocketException: Interrupted function call: Datagram send failed
            at java.net.PlainDatagramSocketImpl.send(Native Method)
            at java.net.DatagramSocket.send(Unknown Source)
            at Main.main(Main.java:23)I don't think this code is supposed to throw a SocketException. When I send a datagram to an invalid IPV4 address, it's not a problem. UDP is connectionless, so I can't figure out the problem here.
    ps.:Working in Windows XP

    The Java Version I'm using is 1.6.0_26 . I'm binding the DatagramSocket because, at the original program, the user may choose which IP address he wants to use as source. I've got over 200 IP addresses in my PC.
    I tried the code without the binding, but the problem persists.
    What did work was running this code on another machine (different network). I ran it on Linux, I was also using Java 6, from Oracle. I just don't remember which update was.
    Could it be a problem with the JVM or the network? IPV6 works just fine if I'm trying to send datagrams to valid addresses or really small datagrams to invalid adressess.
    I don't know whether it is relevant or not, but the IP addresses on my network were manually configured.

  • How can I close DatagramSocket?

    I have DatagramSocket in my WP 8 project. I can open it and receive data but there is no Close() method even though MSDN says it exists. How can I close the socket?
    If I go to the definition of DatagramSocket I see this text at the top of the page:
    #region Assembly Windows.winmd, v255.255.255.255
    // C:\Program Files (x86)\Windows Phone Kits\8.0\\Windows Metadata\Windows.winmd
    #endregion
    The version number seems a bit weird. Am I using wrong assembly?

    If you are programming with C#, you can call datagramSocket.Dispose(), that is the C# projection of
    Close().

  • How to bind DatagramSocket to second NIC?

    I need to bind a DatagramSocket to a second "IPv6-enabled" NIC. Binding to the main "IPv4" NIC works fine but I'm being incapable to change to a different NIC. These are my network settings:
    eth0    Link encap:Ethernet  HWaddr 00:11:43:c8:bd:1c 
              inet addr:192.168.1.17  Bcast:192.168.1.255  Mask:255.255.255.0
              inet6 addr: fe80::211:43ff:fec8:bd1c/64 Scope:Link
              UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
              RX packets:3118 errors:0 dropped:0 overruns:0 frame:0
              TX packets:2608 errors:0 dropped:0 overruns:0 carrier:0
              collisions:0 txqueuelen:1000
              RX bytes:3422763 (3.4 MB)  TX bytes:317046 (317.0 KB)
              Interrupt:16
    lo        Link encap:Local Loopback 
              inet addr:127.0.0.1  Mask:255.0.0.0
              inet6 addr: ::1/128 Scope:Host
              UP LOOPBACK RUNNING  MTU:16436  Metric:1
              RX packets:12 errors:0 dropped:0 overruns:0 frame:0
              TX packets:12 errors:0 dropped:0 overruns:0 carrier:0
              collisions:0 txqueuelen:0
              RX bytes:720 (720.0 B)  TX bytes:720 (720.0 B)
    tun0    Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 
              inet addr:127.0.1.1  P-t-P:127.0.1.1  Mask:255.255.255.255
              inet6 addr: aaaa::1/64 Scope:Global
              UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
              RX packets:0 errors:0 dropped:0 overruns:0 frame:0
              TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
              collisions:0 txqueuelen:500
              RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)I want my DatagramSocket to binded to tun0 so I've tried with
    DatagramSocket mySocket = new DatagramSocket(port, InetAddress.getByName("127.0.1.1"));and
    DatagramSocket mySocket = new DatagramSocket(port, InetAddress.getByName("aaaa::1"));but none of the above methods work: my application is not receiving any UDP traffic on the tun0 interface, at the port specified. I think that binding to a secondary NIC is more complicated than I thought (-:
    Any help is welcome !! Thanks !!
    Daniel.

    Try that method instead getByName and see if you have better luck, keep in mind what the method documentation says about ipv6 addresses.
    getByAddress
    public static InetAddress getByAddress(byte[] addr)
                                    throws UnknownHostException
    Returns an InetAddress object given the raw IP address . The argument is in network byte order: the highest order byte of the address is in getAddress()[0].
    This method doesn't block, i.e. no reverse name service lookup is performed.
    IPv4 address byte array must be 4 bytes long and IPv6 byte array must be 16 bytes long
    Parameters:
    addr - the raw IP address in network byte order
    Returns:
    an InetAddress object created from the raw IP address.
    Throws:
    UnknownHostException - if IP address is of illegal length
    Since:
    1.4This is from the sun api for Java 6 btw. [http://java.sun.com/javase/6/docs/api/]

  • Maximum number of DatagramSockets

    I'm sending a DatagramPacket to 4000 different hosts, and I have successfully multi-threaded (50 threads) the process by having 50 DatagramSockets sending and recieving 50 DatagramPackets every 2 seconds.
    I'd like to up the number to 200 threads (meaning 200 sockets sending/receiving 200 packets every 2 seconds), do you guys think this is an issue? is there a limitation on the number of sockets I have active at a current time?
    Coles Notes: What is the maximum number of DatagramSockets can I run concurrently?
    thanks!
    -M

    how can I use 1 DatagramSocket for N hosts given that I'm multi-threading the operation?You can have multiple threads writing to the same socket. You can have a single thread reading from it and despatching messages to the session threads depending on where the incoming datagram came from.
    doesn't the the connect() method in the DatgramSocket class connect to only 1 host?Of course, but you don't have to call it at all. It doesn't do much.

  • DatagramSocket not working on iOS

    It does not work for me in any of these versions: 16.0, 14.0 and 3.6.
    DatagramSocket.isSupported always returns false.
    Anyone experiencing the same?
    Thanks.

    Found a solution. Package with the SWF with Flash Builder and it works clean and great!
    Tutorial to package SWFs:
    http://renaun.com/blog/2011/05/using-flash-builder-4-5-to-package-arbitrary-swfs-for-ios-a ndroid-and-playbook/
    Flash Builder:
    http://www.adobe.com/products/flash-builder.html

  • Need help with opening DatagramSocket

    Hello I want to make a socket connection this is my code
    public void run()
    int s=0;
    MakeConnection(s);
    In MakeConnection I have thisvoid MakeConnection(int s) throws IOException
    int port =1234;
    DatagramSocket client = new DatagramSocket(port);
    When I compile this code this is said
    unreported exception java.io.IOException; must be caught or declared to be thrown.
    Can anyone help me with this fault.
    And is it possible to get
    int s = client;
    Because when I do it with c I can do
    int s;
    s = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
    en than s is 10 on my computer and in my java code I need to receive s=10 too.

    Do you know what exceptions are? If not, read about them in the Java Tutorial:
    http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html
    In the method run(), you call the method MakeConnection(), which might throw an IOException.
    Since IOException is a checked exception, you must in the method run() specify what you're going to do when an IOException happens. You must either catch the exception (put the call to MakeConnection in a try / catch block) or indicate that run() can throw an IOException by specifying it at the beginning of the method:
    public void run() throws IOException { ...
    But note that you'll just be moving the problem to the method that calls run(). Somewhere in your program you must catch and handle the exception.

  • Flash CS5 + DatagramSocket class error

    As you all know, Flash CS5 is now released. It is confusing me as AIR2.0 is still in beta.
    I tried to use DatagramSocket class but failed
    import flash.net.DatagramSocket
    Up to this point, evrythings ok
    var ds:DatagramSocket = new Datagramsocket()    
    FAILED.
    VerifyError: Error #1014: Class flash.net::DatagramSocket could not be found.
        at runtime::ContentPlayer/loadInitialContent()
        at runtime::ContentPlayer/playRawContent()
        at runtime::ContentPlayer/playContent()
        at runtime::AppRunner/run()
        at global/runtime::ADLEntry()
    I tried replacing the air2 beta 1,air2 beta 2 as stated in the release note but it still fialed..
    Any idea anyone?
    Message was edited by: exerter

    Please check the following links for some answers
    http://blog.tukker.org/2008/05/23/flash-cs3-error-initalizing-java-runtime-environment/
    http://www.actionscript.org/forums/showthread.php3?t=214122
    http://wiki.answers.com/Q/Error_initializing_java_runtime_environment_you_may_need_to_rein stall_flash
    I think the idea is that Flash AS3 compiler needs JRE to compile swfs, so please update to the latest JRE version for CS5 to work. You would not need to install, CS5 Flash again and again.
    Karthik

  • DatagramSocket's MessageReceived event with MF MediaSource strategies?

    I'm trying to integrate sending and receiving data over UDP sockets using Media Foundation.  I've already got my MF MediaSink setup to send data out over a UDP socket.  However, I can't figure out how to get an MF MediaSource to receive data. 
    I'm using a Multicast setup and want to just listen at a single port.  I know how to bind to a service (and I know about the overload for store apps to handle the error with some NICs).  What I don't know how to do is handle the MessageReceived event of
    DatagramSocket via the MF MediaSource.
    From what I can tell, I can't handle it from the MF MediaSource because the MediaSource is a COM class, not a WinRT class... correct?
    So what strategy should I be using?
    1.  I've very briefly tried using a task_completion_event that gets triggered when the message is received.  The MFMediaSource waits for an async method on the UDPClient class I've created to continue after receiving this task_completion_event. 
    I was trying to do something very similar to how the "Simple Communication" sample works for initialiating a connection using a StreamSocket.  However, that was done once and I need my event to loop.  I couldn't get it to work without throwing
    an exception (with not much information).  I'm not sure if it's a deadend.
    2.  Should I create a MemoryStream (whatever the C++ equivalent is) within my UDPClient class, then copy data received over UDP from the IInputStream to my new stream?  I guess I'd have to emply some kind of lock and then poll the new stream
    in a loop from the MF MediaSource. 
    I'm still very much a novice at C++ (trying to learn by example), but I would very much appreciate some help on how to proceed.  Thanks!
    Lee McPherson

    This has helped quite a bit. Thanks for pointing me in the right direction!
    FYI, it would help to create a primer on the history of C++ as it pertains to Microsoft technologies.  I think a lot of people who learn to program now don't necessarily have a formal background in computer programming (mine is in chemistry). 
    I learn from examples and there are plenty of great C++ samples for Windows Store apps, but they are all pretty high level.  I didn't really know until now that they use C++/Cx. I've seen the term before but couldn't make the connection
    as to what it was out of the C++ I was being shown.  I didn't know what WRL was or MFC or any of the other names applied to a flavor of C++.
    The hardest thing about learning over the internet is that you'll get examples written using any number of these... whatever they are called.  Books tend to focus on console apps if they explain COM or WRL.  The ones that use store apps tend to
    focus on C++/Cx and WinRT only.
    All I'm saying is that someone should write a book that explains the non-C++/Cx (and relevant) portions of C++ for Win8.1/WP8.1 to a C# or JavaScript Windows Store app writer . 
    Lee McPherson

  • DatagramSocket API and ServerSocket API

    Based on the release notes of 11.8, the DatagramSocket APIs is now supported on iOS.
    This API is not in the playerglobal.swc available for download @ http://labsdownload.adobe.com/pub/labs/flashruntimes/flashplayer/flashplayer11-8_playerglo bal.swc
    How can I access this API ?
    Reference: http://labsdownload.adobe.com/pub/labs/flashruntimes/shared/air3-8_flashplayer11-8_release notes.pdf
    Thanks.
    Guillaume

    These APIs are already present in AIR desktop.  These will not be available in Flash Player because of the security implications in the context of a web browser running untrusted/unsigned content.
    http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/DatagramSocke t.html
    The DatagramSocket class enables code to send and receive Universal Datagram Protocol (UDP) packets.
    AIR profile support: This feature is supported on all desktop operating systems, but is not supported on mobile devices or AIR for TV devices. You can test for support at run time using the DatagramSocket.isSupported property. See AIR Profile Support for more information regarding API support across multiple profiles.
    http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/ServerSocket. html
    The ServerSocket class allows code to act as a server for Transport Control Protocol (TCP) connections.
    AIR profile support: This feature is supported on all desktop operating systems, but is not supported on mobile devices or AIR for TV devices. You can test for support at run time using the ServerSocket.isSupported property. See AIR Profile Support for more information regarding API support across multiple profiles.

  • How can I unbind port in a DatagramSocket Connection?

    Hi,I often use DatagramSocket and use .close(),.disconnect() and =null to close and release
    the Connection.but i found in many case the port isn't released at all.
    code following:
    DatagramSocket mySocket = new DatagramSocket(7766);
    ....//do something...
    mySocket.close();
    if(mySokcet.isConnected()) serverSocket.ds.disconnect();
    mySocket=null;
    after this,the port 7766 is still binded.why?(not every time,but often)
    can you tell me what shall i do this?

    i just make a mistake,
    DatagramSocket mySocket = new DatagramSocket(7766);
    ....//do something...
    mySocket.close();
    if(mySocket.isConnected()) mySocket.disconnect();
    mySocket=null;
    tell me your way to close connection...thank u very much!!!

  • DatagramSocket problem !!

    Hi,
    When I try to close DatagramSocket which is in receive mode gives me following error
    java.net.SocketException: socket closed
            at java.net.PlainDatagramSocketImpl.receive0(Native Method)
            at java.net.PlainDatagramSocketImpl.receive(Unknown Source)
            at java.net.DatagramSocket.receive(Unknown Source)
            at iCommClient_PWD.PortReader.portRead(PortReader.java:22)
            at iCommClient_PWD.PWDMain.<init>(PWDMain.java:120)
            at iCommClient_PWD.PWDMain.main(PWDMain.java:165)How can I close a socket which is in receive mode ?
    Thanks in advance

    Hi
    I used the following code terminate socket
    if (ds.isConnected()) ds.disconnect();
    if (!ds.isClosed()) ds.close();regards

  • Question about  datagramsocket.receive

    Hi all ,
    I am currently using the datagram socket. I used a server to broadcast one message and hope to receive the response from all my audience within the local network. I used a while loop to keep the server busy receiving the messages from all the clients. I just wonder if this schem would cause some message missing.
    For example, when I received a message from client A and I need to do some extra work on the message A. Before I return to call function socket.receive() to receive another message,the client B's response came in, I just wonder will the java datagram socket got some buffer to handle the extra incoming message before call the function socket.receive(receivePacket)?
    If yes, how large it is?
    Thank you!
    Song Guo

    A DatagramSocket has a receive buffer whose size you can control. On Windows it is a pathetic 8k so you should ceratinly increase it to somewhere close to 64k.
    However you are always going to lose UDP datagrams somewhere or other, and you have to cope with that at the level of your application protocol.

Maybe you are looking for

  • Problem with using javascript in interactive adobe form

    Hi All,     I have a problem when accessing text field value which is present inside a subform using javascript. I tried giving data.page4.sub-5.<fieldname>.rawvalue but its not working. Please provide a solution. Thank you in Advance.

  • Is there a way to preview the dissing of the pages on OAF without deployment ??

    Is there a way to preview the dissing of the pages on OAF without deployment ?? Hi to all, I´m recently  working with OAF and the main server are in Argetina, so when I try to make a deploy  to check the development it takes a lot of time. Is there a

  • VO Extention error

    Hi, i am using apps 12.1.3.i want to create a tengient varible by extending the VO.but when i extend the vo at 4 stape(attribute mapping) gives the error. The error is:*Each row in the Query Result Columns must be mapped to a unique Query Attribute i

  • Show_document without URL

    hello guys, I'm using forms 6i, and i copy certain files into a server and then store the path in my database , now this file can be of different types (doc,pdf,jpg,..etc) the question is how to open this file from client form 6i, as i'm not using ap

  • Changing Name of Computer in Finder

    This is a general question.  I just purchased a new Macbook Air and set it up.  In Finder where my name should be it says "macowner". Is there any way to change that? Thanks