MulticastSocket problem

hi
i'm trying to build a chat application and i have problems with multicast sockets. i.e. when 2 clients are connected to server, the client on wich machine the server is running can see what other client is typing, but the other client can't.
here's the code for the multicastsocket:
socketM=new MulticastSocket(4446);
netIf1=NetworkInterface.getByName("eth0");
netIf2=NetworkInterface.getByName("eth1");
netIf3=NetworkInterface.getByName("eth2");
socketM.joinGroup(group,netIf1);
socketM.joinGroup(group,netIf2);
socketM.joinGroup(group,netIf3);if someone could help me with this i would appreciate

i've deleted the line socketM.joinGroup(group,netIf3);this is how the application should work:
every client sends a packet to the server. the server receives the packet and decides what to do next.
code for sending a packet to the server:
msg="0<"+nickname2+"> "+vText.get(0).getText();
buf=msg.getBytes();
packet=new DatagramPacket(buf,buf.length,address,4445);
try {
       socket.send(packet);
catch(IOException exc) {
       System.err.println("IO exception");
vText.get(0).setText(null);where msg is a String, buf is byte[], vText is Vector<JTextField>.
code for receiving a packet from the server:
packet=new DatagramPacket(buf,buf.length);
socketM.receive(packet);
msg=new String(packet.getData(),0,packet.getLength());
vTxtArea.get(0).append(msg+"\n");where socketM is MulticastSocket, vTxtArea is Vector<JTextArea>.
code for sending a packet from the server to the clients:
group=new InetSocketAddress("230.0.0.1",4446);
//receive a packet from a client
byte[] buf = new byte[256];
DatagramPacket packet=new DatagramPacket(buf, buf.length);
socket.receive(packet);
String dString=new String(packet.getData(),0,packet.getLength());
//send a packet to the clients
buf=dString.getBytes();
packet=new DatagramPacket(buf,buf.length,group);
MulticastSocket sock=new MulticastSocket();
sock.send(packet);
sock.close();i can't find any errors. if you have any ideea why this doesn't work please let me know.

Similar Messages

  • MulticastSocket  problem!! pls help

    suppose a server listening to a port ( say 4444 ) wants to multicast a msg to a group of clients on internet.. then what should b d common group id( Class D ) and port number which all the clients have..

    Before you even start on this make sure your ISP and all the other intervening ISPs support multicast. They generally don't.
    You have to choose your own multicast group address either dynamically via MADCAP or statically.

  • Problems with MulticastSocket and setSoTimeout

    I tried to use a multicast socket to read multicast packets. Everything works fine but there is one strange behaviour: if i try to set a timeout
    with:
    socket.setSoTimeout(8000);
    this call blocks for 8s. And I mean this call, not the receive() method ;-) If i try different timeout it blocks for the new timeout.
    BTW this happens with both the JDK 1.4 on Linux and Win2k
    Any ideas are appreciated
    Marcus

    This is seriously bizarre. In JDK 1.4.1 all that DatagramSocket.setSoTimeout does is set a local variable, doesn't even call the system or enter any JNI.

  • Problem in setup weblogic9.2 MP2 cluster with 2 linux (RHEL4) servers

    Hi All,
              We are trying to setup a clusters of weblogic 9.2 servers on 2 linux machine.
              However we encounter problems when testing load balancing and session replication on the 2 servers.
              We use the configure wizard to configure an adminserver, managed1 server on the 1st linux machine, and managed2 server on the 2nd linux machine. No machine or unix machine is set.
              We are able to start both adminserver, managed1 and managed2 servers.
              And we are able to deploy application to the cluster and run it successfully.
              When we use an apache proxy or the weblogic proxy plugin as an load balancer, we are not able to use the round-robin (load-balancing) features and session replication between the two servers.
              However, when we setup all the servers(adminserver,managed1,managed2) on 1 linux machine, we are enable to use the apahce/weblogic proxy plugin to do round-robin load-balancing and session replication.
              We suspect it is related to multicast.
              When we ping the multicast address setup on each linux machines, we can only see response from the localhost machine.
              When we use util.MulticastTest on linux1 machine, it works properly with only response from linux1 machine.
              When we use the same command util.MulticastTest on linux2 machine, it give the following exception:
              java.net.SocketException: Not a multicast address
              at java.net.MulticastSocket.joinGroup(MulticastSocket.java:273)
              at utils.MulticastTest.<init>(MulticastTest.java:82)
              at utils.MulticastTest.main(MulticastTest.java:233)
              -bash: /bea/weblogic92/server/lib/wlutil.jar: cannot execute binary file
              Both linux servers have no firewall with iptables service stopped.
              Please give us some advices on it.
              Thanks!
              Edited by keatonchan at 12/03/2007 12:12 AM
              Edited by keatonchan at 12/03/2007 12:14 AM

    Just a guess, but it appears the provider-url can specify the cluster name directly, instead of having to specify the individual ports. That's probably a better way to go anyway, but I don't know if it would fix your problem. This is described at [http://e-docs.bea.com/wls/docs90/jndi/jndi.html]

  • MulticastSocket. To whom MC message was sent?

    Hi All,
    My scenarion is:
    1. I created MulticastSocket on port XXXX. (Server side)
    2. Socket was joined to Multicast groups 228.5.6.7 AND 228.5.6.8 (Server side)
    3. Multicast message was sent from another PC to group 228.5.6.7 Client side)
    4. Message received by my MulticastSocket. (Server side)
    The question is How i can to know to which group this message was sent on Server side?
    Continue...
    5. Broadcast message was sent from another PC to "255.255.255.255" (Client side)
    6. Message received by my MulticastSocket. (Server side)
    The question is How i can to know what this is Broadcast message and not from multicast group?
    Continue...
    7. Unicast message was sent from another PC to Server directly by IP (Client side)
    8. Message received by my MulticastSocket. (Server side)
    The question is How i can to know what this is Unicast message and not from multicast group and not from Broadcast?
    I tried to create several MulticastSocket object on same port XXXX and each one was joined to its own multicast group. (First one to 228.5.6.7, and second to 228.5.6.8)
    But then both of then received multicast messages which was sent to 228.5.6.7 OR 228.5.6.8 !!!
    Please Help!!!
    Thanks.

    OK, after spending some time and searching in this forum i found how to fix several of my problems (i bind all sockets to port only and because of this all sockets got everything...)
    But one problem i can't solve.
    The problem that i can't separate from Broadcast messages and multicast messages. So, if i have two Multicast sockets, where one was bound to 228.5.6.8:XXXX and joined to group 228.5.6.8
    and second is for Broadcast only (bound to 0.0.0.0:XXXX) then when i send message to 228.5.6.8 then both of then accept it.
    Is it possible to get only Broadcast message on socket which was bound to 0.0.0.0?

  • Weird error when sending DatagramPackets from a multicastSocket

    hi i got this error when running a program that uses a multicastSocket in different Threads
    the error is java.lang.NullPointerException: null address || null buffer
            at java.net.TwoStacksPlainDatagramSocketImpl.send(Native Method)
            at java.net.DatagramSocket.send(DatagramSocket.java:638)
            at network.Main$LocalServer.runloop(Main.java:363)
            at network.Main$LocalServer.run(Main.java:382)line 363 is
                    DatagramPacket dp=new DatagramPacket(b, 19);
                    System.out.println("LocalServer: Packet created with 19 bytes");
                    sleep(100);
                    SL.send(dp);line 283 is (the run method of LocalServer)
    public void run() {
                runloop();
            }variable SL is created at line 173 in class main.java
    sl=new MulticastSocket(1234);
                System.out.println("local socket created");
                sa=new MulticastSocket(51234);
                System.out.println("global socket created");
                InetAddress g1=InetAddress.getByName("[ff05::1]");
                InetAddress g2=InetAddress.getByName("[ff1e::1]");
                sl.joinGroup(g1);
                System.out.println("local socket group joined");
                sl.setLoopbackMode(true);
                sa.joinGroup(g2);sl is passed to Thread as SL at line 290:
    LocalServer s=new LocalServer(sl);
                s.start();and at line 343
    SL=sl;i am using JDK 1.7.0
    and Netbeans IDE 6.0
    please help me fix this problem!
    thanks in advance for any help

    The DatagramPacket has to be constructed so as to contain the target address.
    MulticastSocket.joinGroup() doesn't help that. It only affects incoming datagrams.

  • Weblogic Clustering Problem

    Hi,
    I am tring to set up clustering on my laptop(Windows XP home OS) using Medrec Tutorials for Weblogic SP4.Its giving me SocketException.Same had worked when tried on Win2000 OS.I tried with SP2 also but its giving the same exception.
    Please let me know if anyone encountered similar pbm and resolved it.Thanks in advance.
    Please find the log below:
    <Jul 29, 2006 11:22:01 PM IST> <Notice> <WebLogicServer> <BEA-000328> <Starting WebLogic Managed Server "MedRec2" for domain "clusterdomain">
    <Jul 29, 2006 11:22:03 PM IST> <Error> <Cluster> <BEA-000116> <Failed to join cluster MedRecCluster at address 230.0.0.1 due to: java.net.SocketException: error setting options.
    java.net.SocketException: error setting options
    at java.net.PlainDatagramSocketImpl.join(Native Method)
    at java.net.PlainDatagramSocketImpl.join(PlainDatagramSocketImpl.java:134)
    at java.net.MulticastSocket.joinGroup(MulticastSocket.java:274)
    at weblogic.cluster.FragmentSocket.initializeMulticastSocket(FragmentSocket.java:92)
    at weblogic.cluster.FragmentSocket.start(FragmentSocket.java:109)
    at weblogic.cluster.MulticastManager.startListening(MulticastManager.java:172)
    at weblogic.cluster.ClusterCommunicationService.initialize(ClusterCommunicationService.java:43)
    at weblogic.t3.srvr.T3Srvr.initializeHere(T3Srvr.java:924)
    at weblogic.t3.srvr.T3Srvr.initialize(T3Srvr.java:670)
    at weblogic.t3.srvr.T3Srvr.run(T3Srvr.java:344)
    at weblogic.Server.main(Server.java:32)
    >
    <Jul 29, 2006 11:22:03 PM IST> <Critical> <WebLogicServer> <BEA-000364> <Server failed during initialization. Exception:weblogic.server.ServerLifecycleException: Failed to listen on multicast address
    weblogic.server.ServerLifecycleException: Failed to listen on multicast address
    at weblogic.cluster.ClusterCommunicationService.initialize(ClusterCommunicationService.java:48)
    at weblogic.t3.srvr.T3Srvr.initializeHere(T3Srvr.java:924)
    at weblogic.t3.srvr.T3Srvr.initialize(T3Srvr.java:670)
    at weblogic.t3.srvr.T3Srvr.run(T3Srvr.java:344)
    at weblogic.Server.main(Server.java:32)
    Caused by: java.net.SocketException: error setting options
    at java.net.PlainDatagramSocketImpl.join(Native Method)
    at java.net.PlainDatagramSocketImpl.join(PlainDatagramSocketImpl.java:134)
    at java.net.MulticastSocket.joinGroup(MulticastSocket.java:274)
    at weblogic.cluster.FragmentSocket.initializeMulticastSocket(FragmentSocket.java:92)
    at weblogic.cluster.FragmentSocket.start(FragmentSocket.java:109)
    at weblogic.cluster.MulticastManager.startListening(MulticastManager.java:172)
    at weblogic.cluster.ClusterCommunicationService.initialize(ClusterCommunicationService.java:43)
    ... 4 more
    >
    <Jul 29, 2006 11:22:03 PM IST> <Emergency> <WebLogicServer> <BEA-000342> <Unable to initialize the server: weblogic.server.ServerLifecycleException: Failed to listen on multicast addresserror setting options>
    The WebLogic Server did not start up properly.
    Exception raised: 'java.net.SocketException: error setting options'
    Reason: weblogic.server.ServerLifecycleException: Failed to listen on multicast addresserror setting options
    Thanks
    Raju

    Hi,
    Actually i tried with Weblogic 8.1 sp2 and sp4 but same problem.I just tried setting up clusters on Windows 2000 it works fine.Seems to be a problem with windows XP home.
    Any idea if same problem occurs with Win XP professional?
    Anyway thanx for the reply.
    Thanks
    Raju

  • MulticastSocket Multicast socket receive error: java.lang.RuntimeException: I/O error opening JAR file from file:/D:/weblogic/mycluster/server86/tmp_deployments/ejbjar-17327.jar

    Hi,
              I need some help.
              Product=weblogic5.1.0
              Revision=(Release Level)=
              Problem Description=
              I am doing cluster of weblogic server, I have no problem to set up the
              cluster and to run servlet and EJB examples.
              However, on my command line for startcluster I got a lot of message as
              followed:
              Fri Aug 18 11:31:44 EDT 2000:<E> <MulticastSocket> Multicast socket receive
              error: java.lang.RuntimeException: I/O error opening JAR file from
              file:/D:/weblogic/mycluster/server86/tmp_deployments/ejbjar-17327.jar
              java.util.zip.ZipException: error in opening zip file
              at java.util.zip.ZipFile.open(Native Method)
              at java.util.zip.ZipFile.<init>(ZipFile.java, Compiled Code)
              at java.util.zip.ZipFile.<init>(ZipFile.java, Compiled Code)
              at weblogic.boot.ServerClassLoader.deploy(ServerClassLoader.java,
              Compiled Code)
              at
              weblogic.cluster.AnnotatedServiceOffer.expandClassPath(AnnotatedServiceOffer
              .java, Compiled Code)
              at
              weblogic.cluster.AnnotatedServiceOffer.readObject(AnnotatedServiceOffer.java
              , Compiled Code)
              at
              weblogic.common.internal.WLObjectInputStreamBase.readPublicSerializable(WLOb
              jectInputStreamBase.java, Compiled Co
              de)
              at
              weblogic.common.internal.WLObjectInputStreamBase.readLeftover(WLObjectInputS
              treamBase.java, Compiled Code)
              at
              weblogic.common.internal.WLObjectInputStreamBase.readObjectBody(WLObjectInpu
              tStreamBase.java, Compiled Code)
              at
              weblogic.common.internal.WLObjectInputStreamBase.readObject(WLObjectInputStr
              eamBase.java, Compiled Code)
              at
              weblogic.common.internal.WLObjectInputStreamBase.readObjectWL(WLObjectInputS
              treamBase.java, Compiled Code)
              at
              weblogic.common.internal.WLObjectInputStreamBase.readArrayList(WLObjectInput
              StreamBase.java, Compiled Code)
              at weblogic.cluster.StateDump.readObject(StateDump.java, Compiled
              Code)
              at
              weblogic.common.internal.WLObjectInputStreamBase.readPublicSerializable(WLOb
              jectInputStreamBase.java, Compiled Co
              de)
              at
              weblogic.common.internal.WLObjectInputStreamBase.readLeftover(WLObjectInputS
              treamBase.java, Compiled Code)
              at
              weblogic.common.internal.WLObjectInputStreamBase.readObjectBody(WLObjectInpu
              tStreamBase.java, Compiled Code)
              at
              weblogic.common.internal.WLObjectInputStreamBase.readObject(WLObjectInputStr
              eamBase.java, Compiled Code)
              at
              weblogic.common.internal.WLObjectInputStreamBase.readObjectWL(WLObjectInputS
              treamBase.java, Compiled Code)
              at weblogic.cluster.TMSocket.execute(TMSocket.java, Compiled Code)
              at weblogic.kernel.ExecuteThread.run(ExecuteThread.java, Compiled
              Code)
              The message freshed about every 20 seconds.
              Another question, I used a iplanet web server as a proxy server with a
              cluster of two weblogic servers pluged in, although I set
              weblogic.properties to round-robin, however, when I run a fibonacci servlet,
              it does not do the round-robin. It always go to one machine for a lot of
              times. Any idea?
              Thank you for your help.
              Tom
              

    May i presume that your cluster is configured on a shared file system?.
              I have seen this problem only if you cluster is configured on different machines
              and if the directory structure is not identical.
              let us know..
              Kumar
              Cameron Purdy wrote:
              > First, update to SP4 (or SP5 if it is out now). Second, follow the cluster
              > instructions on setting up deployments for a cluster. The only
              > implementation that I have used is the single shared location that all the
              > servers load from.
              >
              > --
              >
              > Cameron Purdy
              > http://www.tangosol.com
              >
              > "Tom Gan" <[email protected]> wrote in message
              > news:[email protected]...
              > > Hi,
              > > I need some help.
              > >
              > > Product=weblogic5.1.0
              > > Revision=(Release Level)=
              > > Problem Description=
              > > I am doing cluster of weblogic server, I have no problem to set up the
              > > cluster and to run servlet and EJB examples.
              > > However, on my command line for startcluster I got a lot of message as
              > > followed:
              > > Fri Aug 18 11:31:44 EDT 2000:<E> <MulticastSocket> Multicast socket
              > receive
              > > error: java.lang.RuntimeException: I/O error opening JAR file from
              > > file:/D:/weblogic/mycluster/server86/tmp_deployments/ejbjar-17327.jar
              > > java.util.zip.ZipException: error in opening zip file
              > > at java.util.zip.ZipFile.open(Native Method)
              > > at java.util.zip.ZipFile.<init>(ZipFile.java, Compiled Code)
              > > at java.util.zip.ZipFile.<init>(ZipFile.java, Compiled Code)
              > > at weblogic.boot.ServerClassLoader.deploy(ServerClassLoader.java,
              > > Compiled Code)
              > > at
              > >
              > weblogic.cluster.AnnotatedServiceOffer.expandClassPath(AnnotatedServiceOffer
              > > .java, Compiled Code)
              > > at
              > >
              > weblogic.cluster.AnnotatedServiceOffer.readObject(AnnotatedServiceOffer.java
              > > , Compiled Code)
              > > at
              > >
              > weblogic.common.internal.WLObjectInputStreamBase.readPublicSerializable(WLOb
              > > jectInputStreamBase.java, Compiled Co
              > > de)
              > > at
              > >
              > weblogic.common.internal.WLObjectInputStreamBase.readLeftover(WLObjectInputS
              > > treamBase.java, Compiled Code)
              > > at
              > >
              > weblogic.common.internal.WLObjectInputStreamBase.readObjectBody(WLObjectInpu
              > > tStreamBase.java, Compiled Code)
              > > at
              > >
              > weblogic.common.internal.WLObjectInputStreamBase.readObject(WLObjectInputStr
              > > eamBase.java, Compiled Code)
              > > at
              > >
              > weblogic.common.internal.WLObjectInputStreamBase.readObjectWL(WLObjectInputS
              > > treamBase.java, Compiled Code)
              > > at
              > >
              > weblogic.common.internal.WLObjectInputStreamBase.readArrayList(WLObjectInput
              > > StreamBase.java, Compiled Code)
              > > at weblogic.cluster.StateDump.readObject(StateDump.java, Compiled
              > > Code)
              > > at
              > >
              > weblogic.common.internal.WLObjectInputStreamBase.readPublicSerializable(WLOb
              > > jectInputStreamBase.java, Compiled Co
              > > de)
              > > at
              > >
              > weblogic.common.internal.WLObjectInputStreamBase.readLeftover(WLObjectInputS
              > > treamBase.java, Compiled Code)
              > > at
              > >
              > weblogic.common.internal.WLObjectInputStreamBase.readObjectBody(WLObjectInpu
              > > tStreamBase.java, Compiled Code)
              > > at
              > >
              > weblogic.common.internal.WLObjectInputStreamBase.readObject(WLObjectInputStr
              > > eamBase.java, Compiled Code)
              > > at
              > >
              > weblogic.common.internal.WLObjectInputStreamBase.readObjectWL(WLObjectInputS
              > > treamBase.java, Compiled Code)
              > > at weblogic.cluster.TMSocket.execute(TMSocket.java, Compiled Code)
              > > at weblogic.kernel.ExecuteThread.run(ExecuteThread.java, Compiled
              > > Code)
              > >
              > > The message freshed about every 20 seconds.
              > >
              > > Another question, I used a iplanet web server as a proxy server with a
              > > cluster of two weblogic servers pluged in, although I set
              > > weblogic.properties to round-robin, however, when I run a fibonacci
              > servlet,
              > > it does not do the round-robin. It always go to one machine for a lot of
              > > times. Any idea?
              > > Thank you for your help.
              > > Tom
              > >
              > >
              > >
              

  • Problem in clustering in Weblogic 5.1 (java.util.zip.ZipException)

    Hi All,
    We are using WLS 5.1 clustering. 2 WLS are running in 2 different unix box in same subnet. But we are getting the following exception ( Though all the Beans have been deployed successfully).
    java.util.zip.ZipException: error in opening zip file
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.open(Compiled Code)
    at java.util.zip.ZipFile.<init>(Compiled Code)
    at java.util.zip.ZipFile.<init>(Compiled Code)
    at weblogic.boot.ServerClassLoader.deploy(ServerClassLoader.java:132)
    at weblogic.cluster.AnnotatedServiceOffer.expandClassPath(Compiled Code)
    at weblogic.cluster.AnnotatedServiceOffer.readObject(Compiled Code)
    at weblogic.common.internal.WLObjectInputStreamBase.readPublicSerializable(Compiled Code)
    Fri Jan 25 16:57:22 MST 2002:<E> <MulticastSocket> Multicast socket receive error: java.lang.RuntimeException: I/O error opening JAR file from file:/opt/wlogic/weblogic/obscluster/server113/tmp_deployments/ejbjar-4247.jar
    (cluster name we have changed to obscluster )
    This Exception is coming in both the servers The difference is that the server whose ip ends with 112 is trying to open the file from server113 dir and the server whose ip ends with 113 is trying to open the file from server112 dir.
    In web I have found that if the directory structure of 2 servers doesn't match then this porblem can arise. But for both of my servers the directory structure is same , at least until /opt/wlogic/weblogic/obscluster/ and then the directory server113 or server112 is created by Weblogic automatically when I have started the Server.
    Any help regarding this will be very helpful.
    Thanks & Regards
    Srijeeb.

    Hi everyone,
    I think I have got the solution. Using sp11. added sp11 related jar in PRE_CLASSPATH . Problem Solved....
    Thanks
    Srijeeb

  • Client-Server side programing problem

    I designed a client-server program as seen below basis on serversocket and thread
    I use serversocket for making a host connection than people connect this socket via applet that i designed then they transffer data with socket.getInputStream() and socket.getOutputStream but it always happening between client and server how can i make theese streams transfer between clients is something like that possible if it is how?
    I couldnt send my hole java code because its too long and i wish i could explain my problem
        public void run()
            try
                servsocket = new ServerSocket(port);
                jTextArea1.append("Kullanici Girisi Bekleniyor.\n");
            catch(IOException e)
                jTextArea1.append("Sunucu Uzerinde Socket Acilamadi.\n");
                while(calisiyor)  //calisiyor variable is a boolean variable for checking if server is running
                    try
                    Socket sock = servsocket.accept();
                    background = new techsupportbackground(this,sock);
                    background.start();
                    catch(Exception e)
                        printstring("Hata:"+e);
                        break;
    this is the techsupportbackground classes run method it extends from thread
        public void run()
            if(!servicesetup()) return;
            support.printstring("Baglanti saglandi,kullanici basariyla giris yapti.");
            setPriority(MIN_PRIORITY);
            String sonmesaj = "";
            while(calisiyor)
                String mesaj = readinputline();
                if(mesaj == null) break;
                if (!sonmesaj.equals(mesaj))
                    support.printstring(username+"->"+mesaj);
                    sonmesaj = mesaj;
            cikis();
    and this is the client side program's run method
        public void run()
            try
                if(!doconnection())
                    client.printstring("Baglanti Saglanamadi:");
                    return;
            catch(Exception e)
                client.printstring("Baglanti Saglanamadi");
            while (calisiyor)
                String mesaj = readline();  //readline is the method which reads sockets input stream
                client.printstring(mesaj);
                    if (mesaj == null) break;
                    try {
                    Thread.sleep (client.timeupdate);
                    catch (InterruptedException e)
            if (server != null) closeserver();
            client.setdisconnected();
            client.printstring("Baglanti Koptu");

    I made two java file , one for server one for client
    server is working good openning the socket but the client is crashing when i attempt to connect to server
    here is my code if anyone could tell me where i made a mistake i would be very appreciate
    this is the client program
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.event.*;
    class client extends javax.swing.JFrame {
        private boolean baglandi;
        private MulticastSocket socket;
        private int port;
        private String ip;
        String username;
        private InetAddress group;
        private String msg;
        private DatagramPacket datawriter;
        private byte[] reader;
        private boolean calisiyor;
        private JScrollPane scrollpane;
        public client() {
            initComponents();
            this.setSize(490,450);
            jTextArea1.setEditable(false);
            jTextField2.setEditable(false);
            jButton2.setEnabled(false);
            jLabel3.setForeground(Color.RED);
            JPanel panel = new JPanel();
            panel.setLayout(new BorderLayout());
            panel.setBounds(0, 0, 480, 260);
            getContentPane().add(panel);
            scrollpane = new JScrollPane();
            scrollpane.getViewport().add(jTextArea1);
            panel.add(scrollpane,BorderLayout.CENTER);
            baglandi=false;
            ip="228.5.6.7";
            port=2222;
            try
            group = InetAddress.getByName(ip);
            msg ="";
            datawriter = new DatagramPacket(msg.getBytes(),msg.length(),group,port);
            calisiyor = false;
            catch(Exception e)
        private void initComponents() {
            jTextArea1 = new javax.swing.JTextArea();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jTextField1 = new javax.swing.JTextField();
            jTextField2 = new javax.swing.JTextField();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jButton3 = new javax.swing.JButton();
            jLabel3 = new javax.swing.JLabel();
            getContentPane().setLayout(null);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            getContentPane().add(jTextArea1);
            jTextArea1.setBounds(0, 0, 480, 260);
            jLabel1.setText("Kullanici Adi");
            getContentPane().add(jLabel1);
            jLabel1.setBounds(0, 270, 90, 15);
            jLabel2.setText("Mesaj");
            getContentPane().add(jLabel2);
            jLabel2.setBounds(0, 300, 60, 15);
            getContentPane().add(jTextField1);
            jTextField1.setBounds(100, 270, 290, 21);
            getContentPane().add(jTextField2);
            jTextField2.setBounds(100, 300, 290, 21);
            jButton1.setText("Gonder");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            getContentPane().add(jButton1);
            jButton1.setBounds(400, 270, 80, 25);
            jButton2.setText("Gonder");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
            getContentPane().add(jButton2);
            jButton2.setBounds(400, 300, 80, 25);
            jButton3.setText("Durdur");
            jButton3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton3ActionPerformed(evt);
            getContentPane().add(jButton3);
            jButton3.setBounds(400, 340, 80, 25);
            jLabel3.setText("Baglanti Saglanamadi");
            getContentPane().add(jLabel3);
            jLabel3.setBounds(0, 360, 130, 15);
            pack();
        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
            durdur();
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
            printoutput();
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            baslat();
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            new client().show();
        public void baslat()
            username = jTextField1.getText();
            try
                socket = new MulticastSocket(port);
                socket.joinGroup(group);
            catch(IOException e)
                jTextArea1.append("Guvenlik Engellemesi Sebebiyle Sunucuya Ulasilamadi.\n");
                return;
                    jTextArea1.append("Sunucuya Baglanildi");
                    baglandi = true;
                    calisiyor = true;
                    jLabel3.setText("Baglanti Saglandi");
                    jTextArea1.append("Sunucuya Basariyla Baglanildi\n");
                    jLabel3.setForeground(Color.GREEN);
                    jButton1.setEnabled(false);
                    jTextField1.setEditable(false);
                    jButton2.setEnabled(true);
                    jTextField2.setEditable(true);
                while (calisiyor)
                        String mesaj = readline();
                        printstring(mesaj);
                        if (mesaj == null) break;
        public void durdur()
            jTextField2.setEditable(false);
            jTextField1.setEditable(true);
            jButton2.setEnabled(false);
            jButton1.setEnabled(true);
            jLabel3.setText("Baglanti Saglanamadi");
            jLabel3.setForeground(Color.RED);
            try
                socket.leaveGroup(group);
            catch(Exception e)
        public void printoutput()
            try
            String mesaj = jTextField2.getText();
            jTextField2.setText("");
            writeline(username+":->"+mesaj);
            catch(Exception e)
                printstring("Veri Ulastirilamadi.");
        public void printstring(String s)
            jTextArea1.append(s+"\n");
        public void setdisconnected()
            jTextField2.setEditable(false);
            jTextField1.setEditable(true);
            jButton2.setEnabled(false);
            jButton1.setEnabled(true);
            jLabel3.setText("Baglanti Saglanamadi");
            jLabel3.setForeground(Color.RED);
            public String readline()
                byte[] buf = new byte[1000];
                DatagramPacket datapack = new DatagramPacket(buf,buf.length);
                try
                    socket.receive(datapack);
                    String mesaj = buf.toString();
                    return mesaj;
                catch(Exception e)
                    printstring("Sunucuya Ulasilamadi");
                    return null;
        public void writeline(String s) throws IOException
                try
                    msg = s;
                    socket.send(datawriter);
                    printstring(msg);
                catch(Exception e)
                    printstring("Mesaj ulastirilamadi.");
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton3;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JTextArea jTextArea1;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JTextField jTextField2;
        // End of variables declaration
    this is the server program
    import java.net.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class techsupport extends javax.swing.JFrame implements ActionListener,Runnable {
        private MulticastSocket servsocket;
        private int port;
        private boolean calisiyor;
        private JScrollPane scrollpane;
        private techsupportbackground  background;
        private InetAddress group;
        public techsupport(String title) {
            super(title);
            initComponents();
            this.setSize(400,400);
            port=2222;
            jTextField1.addActionListener(this);
            jButton1.addActionListener(this);
            calisiyor=true;
            jTextArea1.setEditable(false);
            JPanel panel = new JPanel();
            panel.setLayout(new BorderLayout());
            panel.setBounds(0,10,400, 230);
            getContentPane().add(panel);
            scrollpane = new JScrollPane();
            scrollpane.getViewport().add(jTextArea1);
            panel.add(scrollpane,BorderLayout.CENTER);
                try
                group = InetAddress.getByName("228.5.6.7");
                catch(Exception e)
        private void initComponents() {
            jTextArea1 = new javax.swing.JTextArea();
            jButton1 = new javax.swing.JButton();
            jLabel1 = new javax.swing.JLabel();
            jButton2 = new javax.swing.JButton();
            jTextField1 = new javax.swing.JTextField();
            getContentPane().setLayout(null);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            getContentPane().add(jTextArea1);
            jTextArea1.setBounds(0, 10, 400, 230);
            jButton1.setText("Start");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            getContentPane().add(jButton1);
            jButton1.setBounds(160, 260, 80, 25);
            jLabel1.setText("Port");
            getContentPane().add(jLabel1);
            jLabel1.setBounds(0, 240, 120, 15);
            jButton2.setText("Stop");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
            getContentPane().add(jButton2);
            jButton2.setBounds(250, 260, 90, 25);
            getContentPane().add(jTextField1);
            jTextField1.setBounds(0, 260, 130, 21);
            pack();
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
            try
            servsocket.close();
            jButton1.setEnabled(true);
            printstring("Port Kapatildi.");
            jTextArea1.setText("");
            catch(Exception e)
                printstring("Hata:"+e);
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
        public static void main(String args[]) {
            new techsupport("Teknik Destek Sunucu").show();
        public void actionPerformed(ActionEvent e) {
            boolean status = false;
            String komut = e.getActionCommand();
                if (komut.equals("Start"))
                    try
                        port = Integer.parseInt(jTextField1.getText());
                        jButton1.setEnabled(false);
                    catch(NumberFormatException err)
                        jTextArea1.append("Hatali Port Numarasi"+"\n");
                        jButton1.setEnabled(true);                   
                    Thread uygulama = new Thread(this);
                    uygulama.start();
                else if (komut.equals("Stop"))
                    calisiyor=false;
                    dispose();
        public void run()
            try
                servsocket = new MulticastSocket(port);
                servsocket.joinGroup(group);
                jTextArea1.append("Kullanici Girisi Bekleniyor.\n");
            catch(IOException e)
                jTextArea1.append("Sunucu Uzerinde Socket Acilamadi.\n"+e.toString());
        public void printstring(String s)
            jTextArea1.append(s+"\n");
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JTextArea jTextArea1;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration
    }

  • MulticastSocket Class a little hinderence

    I m working with MulticastSocket, sending a single packet over a group of computers or networks (each client)using Multicast IP-Address.
    i am stuck over a point where let suppose a network comprises of 4 clients of same Multicast IP group. any computer joins network, server stores the hostname of the computer in a vector table, and sends that host name and all other hostnames in the vector table "to all other computers already in vector table.."
    moreover if any computer leaves the network,
    it removes the name from the vector table and again sends the remaining hostnames in vectortable to the remaining computers...

    Hopefully that isn't quite what your instructor said. If so
    s/he is simplifying it a bit too much.
    In Flash the framerate is like a brake not an accelerator. It
    is there to stop faster computers from running away at lightning
    speed, not to push slow computers to the rate. If you are having
    problems getting smooth animation increasing the rate (unless you
    start out at 12 or something) almost never is the solution.
    So it is best to find a rate that your target audience's
    computers can handle and stick to that rate. It will be very
    helpful to you in the future if you have just one rate that you
    generally use.
    Back in the day 12 or 15 was pretty decent, but that was back
    in the late 1990s! Today a more appropriate rate is 21, 24, or 30.
    For most purposes 30 is pretty good and is the highest I would
    recommend unless you have specific requirements to go
    higher.

  • Unreliable behavior of MulticastSocket's receive method

    I have a program that uses one MulticastSocket to receive packets from a multicast address on a given port (running on a dedicated thread), and another MulticastSocket to send both multicast- and unicast-adressed packets from the same port (running on a separate thread). The program runs on a Windows system that communicates with a separate program (written in C++) running on a Linux system (more specifically, a Gumstix processor running Ubuntu). Both applications are written to send some messages by multicast, and others by direct unicast, with all sending and receiving being performed using the same port number.
    The problem I'm having is this... The MulticastSocket SOMETIMES receives packets sent by the remote system by BOTH multicast addressing AND unicast addressing, but other times, ONLY receives the packets sent by multicast addressing. By "sometimes" and "other times," I mean "distinct executions of the program." That is, if I run it one time, the MulticastSocket ALWAYS behaves one way, and if I run the same program again, it ALWAYS behaves the other way.
    I know that this smacks of thread-interaction issues, but I have done due diligence to rule this out as best I can.
    All of the documentation about MulticastSocket says that it is perfectly reasonable to create multiple MulticastSockets on the same socket address (i.e., the same port), by virtue of the fact that the class sets SO_REUSEADDR to true by default. But if the code never instantiates the sending MulticastSocket, the receiver seems to receive unicast-addressed packets quite reliably.
    How can I ensure that the receiving MulticastSocket behaves in a predictable manner? Are there known issues with this?

    I don't understand why you're using two MulticastSockets for this. You can send and receive from the same MulticastSocket simultaneously.

  • Setting network interface and ttl for MulticastSocket

    Hello
    I've tried to set the network interface and the TTL for a MulticastSocket, but it has no effect. For testing I set the TTL to '4' and the network interface to 'lo' (localhost), but everybody in the local area network get my message with TTL=1...
    I use Fedora Core 5 (Linux), with no settings in the iptables.
    Here is the code I used:
    private String networkInterface="lo";
    private String address="239.192.0.5";
    private int port=54321;
    private int mcastTtl=4;
    public void send(){
    InputStream input=getContextClassLoader().getResourceAsStream("something.xml");
    byte[] buffer = new byte[1480];
    int length = input.read(buffer,0, 1480);
    inetAddress = InetAddress.getByName(address);
    nInterface=NetworkInterface.getByName(networkInterface);
    MulticastSocket socket = new MulticastSocket(port);
    socket.joinGroup(inetAddress);
    DatagramPacket packet = new DatagramPacket(buffer, length,
    inetAddress, port);
    socket.setTimeToLive(mcastTtl);
    socket.setNetworkInterface(nInterface);
    socket.send(packet);
    socket.leaveGroup(inetAddress);
    For simplicity I took the Error handling off here, but certainly I have it in my code. No errors, no problems, everybody get the correct message... But not with the settings I made.
    Any tips?
    Thanks:
    Bence

    I'm seeing the exact same thing. It's as if setNetworkInterface() doesn't actually do anything at all.
    java version "1.5.0_09"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_09-b03)
    Java HotSpot(TM) Server VM (build 1.5.0_09-b03, mixed mode)
    OS: Linux kernel 2.6.14.3, CentOS 4.2
    Code example (parts removed for clarity) follows. This code works perfectly when I allow it to attach to the default (eth0) interface. When I try to change the interface it binds to, all packets are still multicast to eth0 ONLY! I see nothing on lo or eth1.
    Properties props = System.getDefaultProperties();
    props.setProperty("java.net.preferIPv4Stack","true");
    MulticastSocket mcs = new MulticastSocket(localPort);
    mcs.setNetworkInterface(NetworkInterface.getByName("eth1"));
    InetAddress group = InetAddress.getByName("230.1.1.1");
    String payload = "This is my payload";
    DatagramPacket dgram = new DatagramPacket(payload.getBytes(),
    payload.length(),
    group, groupPort);
    mcs.send(dgram);

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

Maybe you are looking for