Problem using a GUI, a loop and a different thread for the loop

Hi everyone!
First of all sorry if my post is in the wrong forum.
I'm designing a client-server project to allow users to comunicate with each other, and I have a problem in the client class. I'm using the UDP transport protocol, and I'm not allowed to use TCP. The thing is, each client is allowed to send and receive a message at any time, so by pushing a button the "sending event" triggers and sends it, and in order to receive i've launched a receiving process in another different thread, so the sending procces wouldn't be blocked.
This is the code of the client class, called Conversacion:
package mymessenger;
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.lang.*;
import java.awt.*;
import java.util.*;
public class Conversacion extends javax.swing.JFrame {
    private InetAddress MaquinaServidor;
    private int PuertoServidor;
    private DatagramSocket MiSocket;
    private DatagramPacket PaqueteSalida;
    byte [] BufferEntrada= new byte[1024];
    private DatagramPacket PaqueteEntrada= new DatagramPacket (BufferEntrada,BufferEntrada.length);
    byte [] BufferSalida;
    int ack=0;
    int puerto_contrario;
    String direccion="192.168.1.102";
    String direccion_contraria;
    String destinatario_completo="";
    String nombre_destinatario="";
    String nombre_local="";
    String mensaje_recibido=""; // This is the variable I want to use every time a client receives a message
    boolean salir=false;
    public Conversacion()
        initComponents();
        esperar();
@SuppressWarnings("unchecked")
// Here would come the generated code by Netbeans, which is not relevant in this case
private void enviarActionPerformed(java.awt.event.ActionEvent evt) {                                     
   // This is the sending event that calls a function to send the message to the server, i'll post it in another message
    void enviar (String mens) 
        // Function used to send the message to the server, i'll post it in another message
    void esperar() // Here's the problem (I think)
        new Thread(new Runnable() // I launch it in a new thread, so I don't block "enviar"
            public void run() // At first, the client sends some message to the server, so the server knows some data of the client. Go to the while() command please
                String respuesta="";
                try
                    MiSocket= new DatagramSocket();
                    MaquinaServidor= InetAddress.getByName(direccion);
                    PuertoServidor=7777;
                    String comando="ENVIAME LOS DATOS AQUI, A LA CONVERSACION";
                    byte[] na={(byte)(ack%2)};
                    comando= (new String (na))+comando;
                    BufferSalida = comando.getBytes();
                    PaqueteSalida = new DatagramPacket(BufferSalida,BufferSalida.length,MaquinaServidor,PuertoServidor);
                    segsend(PaqueteSalida);
                    ack++;
                    System.out.println("Estoy esperando un mensaje del servidor");
                    segreceive(PaqueteEntrada);
                    String retorno = new String(BufferEntrada, 1,PaqueteEntrada.getLength()-1);
                    int pos= retorno.indexOf("(");
                    int pos2=retorno.indexOf("]");
                    int pos3=retorno.indexOf("Ð");
                    nombre_destinatario=retorno.substring(0,pos-1);
                    destinatario_completo=retorno.substring(0,pos2+1);
                    direccion_contraria=retorno.substring(pos2+1,pos3);
                    nombre_local=retorno.substring(pos3+1);
                    setTitle(destinatario_completo+" - CONVERSACIÓN");
                    segreceive(PaqueteEntrada);
                    respuesta = new String(BufferEntrada, 1,PaqueteEntrada.getLength()-1);
                    puerto_contrario = Integer.parseInt(respuesta);
                    while (!salir) // Here begins the infinite loop I use to receive messages over and over again
                        segreceive(PaqueteEntrada); // I use segreceive that is kind of the same as "receive". No big deal about this
                        mensaje_recibido = new String(BufferEntrada, 1,PaqueteEntrada.getLength()-1); // Every time a client receives a message, I want to store it in the variable "mensaje_recibido"
                        int pos4 = mensaje_recibido.indexOf(":");                     // This next 4 commands are not relevant
                        String auxiliar=mensaje_recibido.substring(pos4+2);
                        if (auxiliar.equals("FINALIZAR CONVERSACION"))
                            setVisible(false);
                        SwingUtilities.invokeLater(new Runnable() // Now I want to asign the value of mensaje_recibido (the message I just received) into texto_total, a Swing text area
                            public void run()
                                String auxi=texto_total.getText();
                                if (auxi.equals(""))
                                    texto_total.setText(mensaje_recibido); // if the text area was empty, then then i put into it the message
                                else
                                    texto_total.setText(auxi+"\n"+mensaje_recibido); // if it's not, then i put the message in the next line of the text area
                        Thread.sleep(1000);
                catch (Exception e3)
                    System.out.println(e3);
        }).start();
    }The communication starts and one user is able to send all the messages he wants to the other one, but when the other wants to send one to the first user, the first user receives a message with the same character over and over again that looks like an square ■. Again, this problem comes when a user that already sended a message, and wants to receive one for the first time (and next times). I searched in these forums all day and so far I couldn't fix it.
This problem happens in the receiver client, not in the sender client and not in the server. I already looked into that and those things are doing what they have to. I would be really really grateful if somebody could tell me which is the problem or how to fix this, because I'm becoming nuts.
Now I'm going to post the function "enviar" which sends the message, and the content of "enviarActionPerformed" which calls "enviar".
Again, excuse me if this is the wrong forum for this question. and sorry for my English too.

This is the rest of the code, though I don't think the problem is here, maybe by pushing the sending button it causes the receiving problem:
private void enviarActionPerformed(java.awt.event.ActionEvent evt) {                                      
        String mensaje=texto.getText();
        mensaje=nombre_local+" dice: "+mensaje;
        texto.setText("");
        String auxiliar=texto_total.getText();
        if (auxiliar.equals(""))
            texto_total.setText(mensaje);
        else
            texto_total.setText(auxiliar+"\n"+mensaje);
        enviar(mensaje);
    void enviar (String mens)
        String respuesta="";
        try
            MiSocket= new DatagramSocket();
            MaquinaServidor= InetAddress.getByName(direccion);
            PuertoServidor=7777;
            BufferedReader Teclado= new BufferedReader(new InputStreamReader(System.in));
            BufferEntrada = new byte[1024];
            PaqueteEntrada = new DatagramPacket (BufferEntrada,BufferEntrada.length);
            BufferSalida=new byte[1024];
            String comando="RETRANSMITIR MENSAJE";
            byte[] na={(byte)(ack%2)};
            comando= (new String (na))+comando;
            BufferSalida = comando.getBytes();
            PaqueteSalida = new DatagramPacket(BufferSalida,BufferSalida.length,MaquinaServidor,PuertoServidor);
            segsend(PaqueteSalida);
            ack++;
            String puerto= Integer.toString(puerto_contrario);
            int pos = mens.indexOf(":");
            String auxiliar=mens.substring(pos+2);
            comando=mens+"-"+direccion_contraria+"*"+puerto;
            byte[] nb={(byte)(ack%2)};
            comando= (new String (nb))+comando;
            BufferSalida = comando.getBytes();
            PaqueteSalida = new DatagramPacket(BufferSalida,BufferSalida.length,MaquinaServidor,PuertoServidor);
            segsend(PaqueteSalida);
            ack++;
            if (auxiliar.equals("FINALIZAR CONVERSACION"))
                setVisible(false);
        catch(Exception e)
            System.out.println(e);
    }I'm gonna keep working on it, if I manage to fix this I'll let you know. Thanks a lot!

Similar Messages

  • I've an apple ID used to buy off iTunes and a mobileme account for the calendars and contacts. How can I move the calendars and contacts to the older apple ID and use it for iCloud?

    I've an apple ID used to buy off iTunes and a mobileme account for the calendars and contacts. How can I move the calendars and contacts to the older apple ID and use it for iCloud?

    If you remeber the password to that Apple ID then follow these steps
    1 - Make sure you have an email address that is NOT an Apple ID
    2 - Go to AppleID.Apple.com
    3 - Where it reads Manage Apple ID - Sign in
    Once you are signed in want to make sure the email address you are wanting to use is NOT set up as a "Recovery/Rescue" email for this account.
    [To check this - Main page where you see Primary ID - below do you see the email address you want to use listed towards the bottom? Yes - Delete / No - Good ./. If made any adjustments "Save" Next on the left select "Password & Security" - Answer your security questions you set up "if you have any" then scroll towards the bottom and check to see if you see the email address you want to use. Yes - Delete / No - Good] <-> Also you can change your password on this page as well. Any adjustments made "Save"
    Once this is done go back to the main page where you should read "Primary ID" and change the email address that is showing to the new email address youo want. "Save" Done
    I learned this not to long ago and worked for me. Hope this helps you!

  • Good Morning.  I'm having a problem using both my Photoshop elements and premiere programs.  I've installed the programs, redeemed my code and entered the serial numbers, and created the adobe log-in.  I am able to open up the organizer without problems,

    Good Morning.  I'm having a problem using both my Photoshop elements and premiere programs.  I've installed the programs, redeemed my code and entered the serial numbers, and created the adobe log-in.  I am able to open up the organizer without problems, but when I try to open up the photo editor (either by trying to open up the program from the main menu, or right-clicking on a photo in the organizer to edit in elements), the program asks me to sign in to adobe (which I can do and it doesn't give an an "incorrect password" or log-in ID error) then accept the terms and conditions.  When I click to accept the terms and conditions, nothing happens and the editor fails to open.  Everytime I click on the program, I get this same "loop" of signing in and accepting T&C's, but the program fails to open.  Any advice?

      Premiere Elements 10 is now 64 bit, but not PSE10.
    Take a look at your scratch disk set-up and if you have a spare volume, allocate that first before the C drive. Elements use scratch disks when it gets low on RAM.
    Click image to enlarge
    Turn off face recognition and the auto-analyzer to improve performance.
    When editing photos or videos check the task manager to see what background processes may be running and end them temporarily if not needed.

  • I am trying to restore an ipod to the factory settings. However I get a message that my username or password is incorrect. I am using my correct Apple id and password.  What is the problem, please?

    I am trying to restore an ipod to the factory settings. However I get a message that my username or password is incorrect. I am using my correct Apple id and password.  What is the problem, please?

    Was that Apple ID and password the original owner of the iPod?  If not, try using the Apple ID and password of the original owner.

  • I am having problems using mov files imported into a project. I get the message "Not rendered" in the Canvas and clip won't play. Can anyone help?

    I am having problems using mov files imported into a project. I get the message "Not rendered" in the Canvas and clip won't play. Can anyone help?

    When clips won't play without rendering in the Timeline, it usually means that the clip's specs don't match the Sequence settings.
    A .mov file could be made from any number of codecs; the QuickTime Movie designation is merely a container for video files of all kinds.  Since FCE only works with the QuickTime DV codec and the Apple Intermediate Codec (AIC) natively, if your mov files aren't one of those two, you need to convert them PRIOR to importing into your FCE project.
    -DH

  • When i listened my music on my ipod nano 4th, It's sound like a used LPwith the distortion. I check my earphone and it's not the problem. I reset my ipod and it's still having the same problem. Does anybobody having a solution ?

    When i listened my music on my ipod nano 4th, It's sound like a used LP with the distortion. I check my earphone and it's not the problem. I reset my ipod and it's still having the same problem. Does anybobody having a solution ?

    From my limited knowledge the iPod Nano has no support for iCloud or wireless transfers- therefore the only means of downloading songs is by hooking it up to the computer by the white cable.

  • I currently use an iPhone, an iPad, and a Mac computer for business.  The three devices have Contacts Managers that sync with each other through both Google and through Mobile Me.  Currently, this has created a mess of duplicate contacts.  Please researc

    I currently use an iPhone, an iPad, and a Mac computer for business.  The three devices have Contacts Managers that sync with each other through both Google and through Mobile Me.  Currently, this has created a mess of duplicate contacts.  Please advise me on the steps necessary for removing these duplicates and establishing a syncing solution that doesn't regenerate the duplicates.  There are several applications available that remove duplicates, but I am not sure which ones work or don't work.  I want information on this, but most importantly I want to understand how to fix this problem permanently.  Also, I read somewhere that Mac's new operating system, Lion, can help deal with duplicates.  I don't have Lion, but I would be willing to get it, if this would fix the problem.

    Had the same problem with 4 devices (two computers, an iPhone and an iPod). The solution is simple: open the Address Book application in your mac, ask it to locate duplicate entries (under one of the top menu items, "edit" I think), and then ask it to consolidate them: it took me all of three seconds after I figured it out: worked like a charm! PS: if you have more than one mac with unconected Address Books, repeating the operation in the second one may be a good idea.
    Message was edited by: mfduran

  • Can some please provide instructions on how to import an iPhoto library from an old Mac to a new Mac without getting a bunch of duplicates?  I tried transferring my pictures using an external hard drive and then copying it to the Pictures folder on my Mac

    Can someone please provide instructions on how to import an iPhoto library from an old Mac to a new Mac without getting a bunch of duplicates?  I tried transferring my pictures using an external hard drive and then copying it to the Pictures folder on my new Mac.  I ended up getting a bunch of duplicates. My old Mac has an older version of iPhoto while the new Mac has iPhoto '11.  Is that the cause of the problem?  Please advise.  Thanks.

    Simply copy the iPhoto Library from the Pictures Folder on the old Machine to the Pictures Folder on the new Machine.
    Then launch iPhoto. That's it.
    This moves photos, events, albums, books, keywords, slideshows and everything else.
    Regards
    TD

  • My iPod will not charge at all it will when it's off it will power on and charge to a certain pint then will stop and no longer charge what is its problem I've tried 3 cords and three different outlets and also in my computer! What is wrong with it?

    My iPod will not charge at all it will when it's off it will power on and charge to a certain pint then will stop and no longer charge what is its problem I've tried 3 cords and three different outlets and also in my computer! What is wrong with it?it won't charge when it's powered on only when it s off then it turns on and stops charging?? What's wrong with it ad how much is a Genius Bar appt at apple stores??

    Not Charge
    - See:      
    iPod touch: Hardware troubleshooting
    - Try another cable. Some 5G iPods were shipped with Lightning cable that were either initially defective or failed after short use.
    - Try another charging source
    - Inspect the dock connector on the iPod for bent or missing contacts, foreign material, corroded contacts, broken, missing or cracked plastic.
    - Make an appointment at the Genius Bar of an Apple store.
      Apple Retail Store - Genius Bar 

  • Using different templates for the desktop and phone versions of the same blog

    I have a site which was created in Adobe Muse and is hosted on Business Catalyst.
    I have created both a desktop and a phone versions of the site.
    I  want to know how I can integrate the blogs that I  currently have on the desktop site with the phone version that I just did, using different templates for the desktop and phone versions of the same blog. This is in order to ensure that visitors to the blogs on the website are directed to the templates that render correctly for the devices they are using.
    My current approach has been to create both a desktop and phone versions of the blogs. The problem with this however, is that the dates are different and the comments are separated between the two blog versions!
    I  have also tried enabling mobile templates in BC, but still couldn't find a way to specify the mobile versions of the templates for the same blog?
    To recap my problem, I basically  need a solution where the same blog uses different templates for desktop and mobile (both templates use different navigation headings and menu styles)
    Thanks.

    There can be few reason for this, including page contents links or contents used in phone/tablet version.
    Please provide the site url , also try to publish the site as a trial site in Business Catalyst with all layouts which would help to isolate the issue.
    Thanks,
    Sanjit

  • I am building a website using IWEB, on my computer, and I am stuck suddenly, the page I made yesterday is hidden by another page and I cannot pursue.. Is there a way to learn the process, also I see a contradiction with ILIFE 2011, reading about an announ

    I am building a website using IWEB, on my computer, and I am stuck suddenly, the page I made yesterday is hidden by another page and I cannot pursue..
    Is there a way to learn the process, also I see a contradiction with ILIFE 2011, reading about an announcement of Steve Jobs....? that iWeb would not longer be??

    How is the first page hidden by the other page?  Where are you experiencing this problem?  In iWeb's window or in the browser window of the published site? 
    Are you referring to the page's link in your navbar?  If so check the Inspector/Page/Page pane for the "hidden" page and make sure it's set to be included in the navbar. If that's not the problem describe in detail what you mean and include any screenshots you can make of the problem.
    As far as the longevity of iWeb read the following:
    As you now know iWeb and iDVD have been discontinued by Apple. This is evidenced by the fact that new Macs are shipping with iLife 11 installed but without iWeb and iDVD.
    On June 30, 2012 MobileMe will be shutdown. HOWEVER, iWeb will still continue to work but without the following:
    Features No Longer Available Once MobileMe is Discontinued:
    ◼ Password protection
    ◼ Blog and photo comments
    ◼ Blog search
    ◼ Hit counter
    ◼ MobileMe Gallery
    Currently if the site is published directly from iWeb to the 3rd party server the RSS feed and slideshow subscription features will work. However, if the site is first published to a folder on the hard drive and then uploaded to the sever with a 3rd party FTP client those two features will be broken.
    All of these features can be replaced with 3rd party options.
    There's another problem and that's with iWeb's popup slideshows.  Once the MMe servers are no longer online the popup slideshow buttons will not display their images.
    Click to view full size
    However, Roddy McKay and I have figured out a way to modify existing sites with those slideshows and iWeb itself so that those images will display as expected once MobileMe servers are gone.  How to is described in this tutorial: iW14 - Modify iWeb So Popup Slideshows Will Work After MobileMe is Discontinued.
    NOTE: the iLife 11 boxed version Is no longer available at the online Apple Store.  To get a copy you'll have to try Amazon.com or eBay.com.
    This may be of interest to you: Life After MobileMe.
    OT

  • Printer is overprinting old jobs on top of new jobs.  Using a Mac with OSx and a HP photosmart for over a year.  this just started happening.

    Printer is overprinting old jobs on top of new jobs.  Using a Mac with OSx and a HP photosmart for over a year.  this just started happening.

    RReset printing system again and the restart in Safe Mode . This will clear some caches,to do this hold down the Shift key when you hear the startup tone until a progress bar appears, after it has fully booted restart normally and add the printer.

  • I am using OSX 10.9.5 and Outlook Web App for emails. When I download an attachment it replaces the space in the file name with   - how can I change this?

    I am using OSX 10.9.5 and Outlook Web App for emails. When I download an attachment it replaces the space in the file name with %20  - how can I change this?

    Click on the below link :
    https://get.adobe.com/flashplayer/otherversions/
    Step 1: select Mac OS  X 10.6-`0.`0
    Step 2 : Safari and FIrefox
    Then click on " Download Now"  button.

  • HT4623 An Apple pop up keeps coming up anytime I try and use my phone and it has an old Apple ID and it is asking for the password. How do I get it to stop?

    An Apple pop up keeps coming up anytime I try and use my phone and it has an old Apple ID and it is asking for the password. How do I get it to stop?

    That means there is content on your phone...music and or apps...originally obtained using his Apple ID. Such content is forever tied to the account used to originally obtain it and cannot be transferred to another Apple ID. Your only choice is to identify and delete this content.

  • Have new Airport Extreme via ethernet cable from HughesNet Gen4 modem. Using NetGear WN3500RP extender. NetGear asks for different names for the 2.4 and 5 GHz bands. Most of what I have read indicats extender shoul have same name as main network?

    Have new Airport Extreme conneted via ethernet cable from HughesNet Gen4 modem. Using NetGear WN3500RP extender. NetGear asks for different names for the 2.4 and 5 GHz bands. Most of what I have read indicates extender should have same name as main network? How is it best to configure with the Airport Extreme router 802.11ac?

    Different names for the 2.4 and 5 GHz networks are optional, but can be convenient for you to distinguish one from another. It's up to you.

Maybe you are looking for

  • Data Retractors from BPC 7.5 to ECC 6.0

    We are looking for customers who can share infomation that have successfully built automated data retractors from BPC 7.5  to ECC  6.0. There is one whitepaper titled "How to... Retract data from BPC 7.5 NetWeaver to SAP ERP Cost Center Accounting, P

  • How to create multiple copies of a file with renamed filenames

    hi,  I want to create multiple copes of a  file [ say abc.docx] which has 3.5 MB of size  and want to rename it through power shell. so, in the end, i want to get abc_1.docx,abc_2.docx, abc_3.docx ....abc_10.docx in the same folder with the same size

  • JavaFX RMI

    Hi, how can I invocate remote methods from my JavaFX application to a web server? I know that there's an article about, at http://java.sun.com/developer/technicalArticles/scripting/javafxpart2/ but link doesn't work... Anyone can help me??? Thanks in

  • Scaling in reports BPC5 Versus BPC7NW

    I copied the BPC5.1 reports and using in BPC7NW. Though all 5.1 reports are working after copying to BPC 7NW  ..some reports are having issues with scaling. In 5.1 reprots the scaling is defined in reports in the 'scaling control' property in reports

  • ICal problem setting up google account.

    I have OS 10.8.5.  Have gotten the following message when I try and configure my gmail calendar with ical:  account can't be saved to disk. check console for errors. account already exists.  Any thoughts on how to resolve.