removing the objectoutputstream collection intake

Hey guys, I have problems to remove a connection.

How his installation:

first of all I'm doing a chatclient where several users can enter and use for cat
When the client is connected to chatserver

an ArrayList is used to keep track off the coast of socket (objectoutputStream), so the Chatserver can write objects for them later.
So what exactly happens, is when the server accepts the socket, I create objectoutputstream as shown below and add it to ObjectoutPutstream ArrayList, so objects can be written later to these customers. But the problem occurs when I disconnect one of the customers. Objecoutputstream ArrayList still has disconnected and related customer tries to write objects in client disconnected, which then results in an exception. I tried everything and can not find a way to remove the client disconnected from collection objectoutputstream.

What I tried
I tried to use sockets instead of objectoutputstream collection that is a socket becaouse has a connected called method that returns a Boolean value, it sends a null object to the client. weird, isn't it?

ServerSocket serverScoket = new ServerSocket(5000);

Socket clientSocket = serverSocket.accept();//accepting socket

ObjectOutputStream stream = new ObjectOutputStream(clientSocket.getObjectOutputStream));

objectoutputstreamList.add(stream);//adding stream to collection of objecoutputstream
Code of IM client we help to debug
package ChatClient;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import testingchat.UserInfo;


public class ChatClient {

    ObjectOutputStream sendPacket = null;
    ObjectInputStream comingPacket = null;
    Socket clientSocket = null;
    UserInfo checkingUserName = null;

    //connection details
    private int portNumber;
    private String serverIp;
    /**
     * Constructor
     */
    public ChatClient(){
    }

    /**
     * We contact the server and try send data through stream
     */
    public void makeConnection(){
        try{
            clientSocket = new Socket(serverIp,portNumber);
            sendPacket = new ObjectOutputStream(clientSocket.getOutputStream());
            comingPacket = new ObjectInputStream(clientSocket.getInputStream());

            Thread newThread = new Thread(new PacketReader());
            newThread.start();
            System.out.println("networking established");
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * Sending packet to the server
     */
    public void sendPacket(UserInfo userPacket){
        try {

            sendPacket.writeObject(userPacket);
            System.out.println(userPacket.getUserName());
        } catch (IOException ex) {
        }
    }

    public class PacketReader implements Runnable{
         public void run() {
            try {
                UserInfo user;
                while((user = (UserInfo) comingPacket.readObject()) != null){
                    checkingUserName = user;
                    System.out.println(checkingUserName.getUserName()+" inside emthod packetReader");
                }
            } catch (Exception ex) {
            }
        }
    }

    /**
     * @param setting up portNum
     */
    public void setPortNum(int portNum){
        portNumber = portNum;
    }

    /**
     * @param setting up serverIp
     */
    public void setServerIp(String serverIp){
        this.serverIp = serverIp;
    }

    /**
     * Sending messages to user client user interface
     */
    public UserInfo sendUserInfo(){
        return checkingUserName;
    }

    /**
     * Checking UserName Valid
     */
    public boolean checkValidName(){
        System.out.println(checkingUserName);
       return checkingUserName.isUserValid();
    }

    
}
Code for chatserver
package testingchat;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;

/**
 *
 *
 */
public class ChatServer {
    //To write objects to client
    private ArrayList<ObjectOutputStream> streamList;
    private ArrayList<UserInfo> totalUsers;
    /**
     * Constructor
     */
    public ChatServer(){
    }

    /**
     * making contact with client
     */
    public void makeConnection(){
        try {
            streamList = new ArrayList<ObjectOutputStream>();
            ServerSocket serversocket = new ServerSocket(5000);
            System.out.println("connecting to client......");
            while (true){
                Socket client = serversocket.accept();
                System.out.println("made a connection");

                ObjectOutputStream stream = new ObjectOutputStream(client.getOutputStream());
                streamList.add(stream);

                Thread newThread = new Thread(new ClientHandler(client));
                newThread.start();
            }
        } catch (IOException ex) {
        }
    }
    
    public static void main(String[] args){
        new ChatServer().makeConnection();
    }

    public class ClientHandler implements Runnable{
        Socket clienti = null;
        ObjectInputStream stream = null;
        public ClientHandler(Socket sock){
            totalUsers = new ArrayList<UserInfo>();
            clienti = sock;
            try{
                stream = new ObjectInputStream(clienti.getInputStream());
            } catch(Exception e){
            }
        }
        public void run(){
            try {
            UserInfo userinfo = (UserInfo) stream.readObject();
            totalUsers.add(userinfo);
            if(userinfo.isCheckingForValidName()){
                System.out.println(userinfo.getUserName()+"inside chatserver line 66");
                confirmUserName(userinfo);
            }else if(userinfo.isUserValid()){
                     sendToClient(userinfo);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        }

        public void sendToClient(UserInfo user){
            Iterator it = streamList.iterator();
            while (it.hasNext()){
            try {
                ObjectOutputStream objectWriter =  (ObjectOutputStream) it.next();
                objectWriter.writeObject(user);
                objectWriter.flush();
            } catch (Exception ex) { ex.printStackTrace(); }
        }
        }

        /**
         * Informs the login client whether any user with a incoming name is
         *
         */
        public void confirmUserName(UserInfo oCheckUser) {
            try {
                for (UserInfo users : totalUsers) {
                    if (oCheckUser.getUserName().equals(users.getUserName())) {
                        oCheckUser.setUserValid(false);
                    } else {
                        oCheckUser.setUserValid(true);
                        oCheckUser.setCheckingForValidName(false);
                    }
                    //writing objects to client
                    for (ObjectOutputStream outGoing : streamList) {

                        outGoing.writeObject(oCheckUser);
                        outGoing.flush();
                    }
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
userInfo class, is the client object that sends to the server and server sends to clients deferential
package testingchat;
import testingchat.*;
import java.io.Serializable;
/**
 *
 * 
 */
public class UserInfo implements Serializable{

    private String userName;
    private String message;
    private boolean checkingUserName;
    private boolean isUserValid;

    /**
     * Constructor
     */
    public UserInfo(){
        checkingUserName = true;
        isUserValid = false;
    }

    /**
     * Sending message to users
     * @param sMessage
     */
    public void sendMessage(String sMessage){
        message = sMessage;
    }

    /**
     * setting up user's Name
     * @param userName
     */
    public void setUser(String userName){
        this.userName = userName;
    }

    /**
     * @return message
     */
    public String getMessage(){
        return message;
    }

    /**
     * @return userName
     */
    public String getUserName(){
        return userName;
    }

    /**
     * @param oCheckingName
     */
    public void setCheckingForValidName(boolean oCheckingName){
        checkingUserName = oCheckingName;
    }

    /**
     * @return checkingUserName
     */
    public boolean isCheckingForValidName(){
        return checkingUserName;
    }

    /**
     * @param userValid
     */
    public void setUserValid(boolean userValid){
        isUserValid = userValid;
    }

    /**
     * @return isUserValid
     */
    public boolean isUserValid(){
       return isUserValid;
    }

}
Bravo guys, some help would be really appreciated

The title of your son and the question that you ask, is how to remove something from a collection. I responded to it, not that it be answered if you read the Javadoc.

What you want to know but have never actually asked is when* to remove from the collection. The answer is when you read EOS or get an IOException reading or writing of the connection.

You will find that when you express yourself clearly, you will get clear answers. You will also write better code...

Tags: Java

Similar Questions

  • How to remove the music in the Collection Cloud Xbox?

    Does anyone know how to remove songs from the Collection of clouds Xbox? Here's what I did that did not work.

    On my desk, I guess Xbox Music added my existing Xbox content to my Collection of Xbox clouds. I deleted all my content but I did some of it in the Xbox Music and some of them outside by simply deleting the music files. I then restarted Xbox Music. It then downloaded again a part of the music. This time, I deleted the music of Xbox Music. Of course music removed and did not return. However when I plugged my tablet to Xbox Music it download music.
    How to erase songs on the online Xbox cloud Collection so he will leave added these files on my phone and my tablet. They appear on my desk more. I thought to remove the Tablet, but I want to see what others say first.

    Ah ha! I uninstalled the music app and then re-installed. My Collection of clouds Xbox now works as expected. Somehow he thought that it had already downloaded the files.

  • Remove item in the ArrayCollection collection

    Hello!

    Fact: myAC [3] = null actually remove the item from the AC?

    And by this I mean to remove completely the element with key 3.

    For example, if the captain had 5 items: 0,1,2,3,4, myAC [3] = null not what happens at HQ?

    (A) 0,1,2,4

    -or-

    (B) 0,1,2,3, where 3 is the former 4?

    Thank you!

    No it's not.

    This will just set the third element to null. If neither A or B will occur.

    The result will be 0,1,2,3,4, with myAC [3] is nothing.

    Removing an element from a collection ArrayCollection should be done using the removeItemAt method.

  • How to remove the calendar program in the e-mail section because I hate and that everything he did to the e-mail page

    all this happened on my email page yesterday and I clicked it, but I don't like it. and then all of a sudden Besides my collected email addresses and my personal address book now there's a "address book all the" I don't like it as it is constantly changing for it and I don't want that. I want my program to return to how it was three or four days ago, when I didn't have this program and the additional topics, etc.

    How to remove the calendar program

    Open the Add-ons - Extensions Manager, search for 'Flash' and press the 'delete '.

  • I imported my address books. How can I remove the default empty

    I imported my address from my old computer books in Thunderbird on my new computer. Empty default address books don't seem to be able to be deleted, so I have now two books personal address and two collected addresses, the first of all is the default value for empty one and the second is my populated version. Thunderbird seems to point to the default empty. How can I remove the empty for default Thunderbird to my places.

    Thank you

    I don't think you can remove the default books. I open any personal book, select a contact, do a control + a to select all and drag in the personal address book by default. Then delete the empty book. Then do the same for the collected books.

  • How to remove the other yellow section in stock

    Hello

    I want to know if there is a solution to remove the other space, if it is not mandatory in the mac!

    Thank you for helping me with the steps

    Re-index the disk: Spotlight - how to re - index folders or volumes - Apple Support.

    Note that the other represents a category of collection of all things on the volume that does not fit in the other categories: which is 'Other' and what I can do about it?-Apple Support communities

  • Remove the first 5 blocks in a data stream

    Hi all

    I have a problem to remove the first 5 blocks in the data stream. My sampling rate is 1 s, block size is 1 and the entrance is the module «the ddf file read»

    I use the following modules for an average analysis 30 years running.

    [read the folder]---> [Formule1] -> [set variable] -> [formula2]

    |                 ^

    --> [time]-|

    module parameter

    ======                =========

    delay of 30

    Formula1 ${var_1} + in (0) - in (1)

    the value of variable ${var_1}

    Formula2 in (0) / 30

    This configuration is used for channels 13 and one of these channels is used for purposes of triggering. Due to the nature of the variable defined and read in the underlinedmodules, the trigger sequence is delayed for 2 sec. Since I used the trigger to collect the last returns average of each channel, it is now mixed with 2 sec for the next round.

    My question is: is there a way to reduce say 5 blocks of data from the stream? Please help and have a nice day

    Look at the SEPARATE module in the Group of data reduction.

    It allows you to set up an initial leap, then a current break.

    To do this, you want to jump 5 blocks once, does through go zero blocks... who spends the first five and then release all the data blocks of subsequence.

  • How to remove the full features of SigExp project

    We bought a USB-6210 and installed Eval SignalExpress version. I gathered data for a project and assess various data logs. I was apparently using some of the features of the full edition, such as filters. However, I now know that the limited version allows only one newspaper per project, which could be a problem too since I have collected several newspapers in the same project. When I returned from vacation, I found that my eval period expired, and now the project will not open because it has no full functionality in it. I need my back from the raw data. How can I remove the steps long before I can get to my data using the limited version? I really the full version and would like to buy, but your price is widely affordable.

    Kind regards

    Dave

    If you used the SignalExpress logging feature to back up your data, it was stored separately from the project.  You can find it in time-stamped records under your \SignalExpress data file.  You should be able to open the TDMS with Excel files using the Excel that installed in SignalExpress plug-in.  Alternatively, you can open using all that supports the PDM.

    If you used the snapshot functionality, the data is saved in your project.  Post your project and we will remove it for you.  Please let us know which format you want as it in this case.

    On a side note, what do you consider a reasonable price for the software?

  • How to remove the keyboard in a m6 desire?

    Hello

    It's all in the title really. My 'f' key does not work and I would remove it to check I have here something is poorly located below. How should I proceed?

    Thanks in advance.

    The keyboard is not a collection of parts that can be repaired or replaced individually. It is a unit. If you don't know what's down there, so there no reason to delete a key. What is that a flat area in metal. The wheels are on circuit inside the keyboard where you can't reach. I've seen too many people is back in a corner by removing the keys that are pretty darn almost impossible to replace. They stand in a easier way that they return. It is not uncommon that keyboard problems appear as a simple failure or keys just a couple defective.

    The only thing you can do is to reset the computer. Remove the battery and the AC adapter / CC. Press and hold the power for 30 seconds. Replace AC and power. Go into the BIOS and reset the default settings to the output. When it does start, go into the Device Manager and remove the keyboard as a device, restart again and let the driver to reload. This means maybe 5% chance of restoring function.

  • Zoo Tycoon 2: the zookeeper Collection installs, works to the contrary uninstall

    good so I had problems to run the game (I have now found that an update of Avast has been preventing running games so I have to turn everything off first, before running some of my games). so I uninstalled. only when I went to install Collection of Zookeeper (looking to skip a step, since it's three games in one) I click on install, and instead, it asking me questions for uninstall and is yet to install the program

    so today I tried to install Zoo tycoon 2, the base game and installed. Then I tried zookeeper collection. It does the same thing. I tried my missing pets and that it has installed. I'll try the zookeepers collection once more. but my hopes are not up. for some reason, I can't collection of tea another Zookeeper downloadable thing going through the stage of uninstall to remove parts saved, and content.
    I want to know how to get my installed ZooKeeper collection because I really want my African adventures and endangered species.
    I was able to overcome this problem by following these steps for Windows 7. First, go to the control panel and uninstall all the programs related to Zoo Tycoon. Then, type "regedit" in the search box after clicking on the button 'start '. You can search "zoo" and delete the entries that correspond to the "CLEAR" Zoo Tycoon, nothing else. Then go to the computer, then the drive Local (c), then Program Files (x 86), then the information of InstallShield. A list of folders will fill. Look at the dates and try to determine where you originally installed Zoo Tycoon 2 and delete these folders. So try and re - install Zoo Tycoon 2 and it should install correctly. Apparently, the developer, Blue Fang Games, neglected aspects of the use of InstallShield and program still considers that it is installed by looking at the InstallShield folder that was created when you initially installed the game! By deleting this file, it will install then.
  • Computer stops after removing the hardware device.

    Original title: closure of the problem

    Once I am done using bluetooth and easy then disable the bluetooth in my laptop sony vaio, my laptop keeps. It is stuck on the "shutting down" screen and stays just like that. In this case only everytym I use the bluetooth.s

    Hello

    Thanks for asking! If I understand correctly, you have a problem with the computer to close after removing the Bluetooth device.

    Before I continue, I would like to collect some personal information.

    1. Were there of the last changes made to the system before the show?
    2. You get the error message?
    3. The question is limited to specific device?

    Method 1:

    Follow the link to perform a clean boot check, if it helps.

    How to perform a clean boot for a problem in Windows Vista or Windows 7

    http://support.Microsoft.com/kb/929135

    Note: Once you are done with the boot, follow step 7 in the link to your computer in normal mode.

    Method 2:

    Follow this update of the driver update Bluetooth drivers. Check if it helps.

    Answer with the results, I would be happy to help you further.

  • Remove the disks - task does nothing?

    I have a workflow that takes a vm (u_vm below) and an array of strings (u_ldevs below).  It removes the disks of the virtual machine that resident on data warehouses where the last 4 digits match a string in the table provided (u_ldevs).  (in case you're wondering, ldev is a 4-digit hexadecimal number that corresponds to the id of the LUN on the storage array, and we add at the end of each data store name)

    System.log messages in the loop to output the data you expect. all records to be deleted are correct and the appliance.  The task is executed successfully (and I see successful in vSphere), however the VM is unchanged.  I added a loop of debugging downstairs to iterate on the devices to validate the specification contains what I put in, but this lower node does not return any data, which makes me think I'm missing something really stupid.  Can someone take a look?

    System.log(u_vm.name)
    var spec = new VcVirtualMachineConfigSpec();
    spec.deviceChange = [];
    var ix = 0;
    
    
    for each (var device in u_vm.config.hardware.device)
    {
      if (device instanceof VcVirtualDisk)
      {
           if (device.backing instanceof VcVirtualDiskFlatVer2BackingInfo)
           {
                var dsname = device.backing.datastore.name;
                var possibleLdev = dsname.substring(dsname.length-4, dsname.length);
                for each (var ldev in u_ldevs)
                {
                     if (ldev == possibleLdev)
                     {
                          var devChange = new VcVirtualDeviceConfigSpec();
                          devChange.operation = VcVirtualDeviceConfigSpecOperation.remove;
                          devChange.device = device;
                          spec.deviceChange.push(devChange);
                          System.log("Found " + dsname); // this prints the datastore name
                          System.log("device: " + device.deviceInfo.label); // this prints the device label "Hard Disk #"
                     }
                }
           }
      }
    }
    
    for (var ix in spec.deviceChange) // have also tried a for each (var devChange in spec.deviceChange) ...
    {
      System.log('dev change:'); // this never prints
      System.log('dc op: ' + spec.deviceChange[ix].operation.value); // this never prints
      System.log('dev: ' + spec.deviceChange[ix].device.deviceInfo.summary); // this never prints
    }
    
    
    task = u_vm.reconfigVM_Task(spec);  // this run successfully
    

    I think that the problem is somehow related to the fact that vRO script properties table are not exactly identical to the normal Javascript table properties.

    A possible solution would be to collect device configuration specifications not directly in the spec.deviceChange property, but in a simple Javascript temporary table and assign the entire table to spec.deviceChange after the first loop.

    Something like this:

    System.log(u_vm.name)
    var spec = new VcVirtualMachineConfigSpec();
    myDeviceChanges = [];  // <- plain Javascript array
    var ix = 0;  
    
    for each (var device in u_vm.config.hardware.device)
    {
      if (device instanceof VcVirtualDisk)
      {
           if (device.backing instanceof VcVirtualDiskFlatVer2BackingInfo)
           {
                var dsname = device.backing.datastore.name;
                var possibleLdev = dsname.substring(dsname.length-4, dsname.length);
                for each (var ldev in u_ldevs)
                {
                     if (ldev == possibleLdev)
                     {
                          var devChange = new VcVirtualDeviceConfigSpec();
                          devChange.operation = VcVirtualDeviceConfigSpecOperation.remove;
                          devChange.device = device;
                          myDeviceChanges.push(devChange);
                          System.log("Found " + dsname); // this prints the datastore name
                          System.log("device: " + device.deviceInfo.label); // this prints the device label "Hard Disk #"
                     }
                }
           }
      }
    }  
    
    spec.deviceChange = myDeviceChanges; // <- assign collected device config specs at once
    
    for (var ix in spec.deviceChange) // have also tried a for each (var devChange in spec.deviceChange) ...
    {
      System.log('dev change:'); // this never prints
      System.log('dc op: ' + spec.deviceChange[ix].operation.value); // this never prints
      System.log('dev: ' + spec.deviceChange[ix].device.deviceInfo.summary); // this never prints
    }  
    
    task = u_vm.reconfigVM_Task(spec);  // this run successfully
    
  • Possible to remove the top card, title bar and navigation?

    Hi, with is the new beta version of DPS possible to open the article without going through a card/article summary page to interact with?

    In the previous version of the DPS, you could specify some of these options.

    Ideally, I would like to remove:

    • The title bar
    • Interaction with the card - directly in the full experience
    • And remove the net asset value of high level 'Done' feature


    Miss me just something hope.


    Thanks for any help!

    Hello

    Instead of jumping into the list of cards for a collection (the so-called Page Browse), there is a setting on the collection of jump in the first article. Essentially, this allows to bypass the page browse and opens the first item in the collection.

    For now, there is not a way to disable the application user interface.

    Andrei

  • How to remove hidden links (how to remove the links, ONLY the hidden parts of the document)

    in Acrobat XI-> after deletion "text hidden" using the tool 'Remove hidden information'-> links still remain in the hidden passage / cropped -> so the real question is - HOW TO REMOVE THE LINKS HIDDEN in a PDF. An approach may be to remove 'links, Actions and Javascripts' tool 'Remove' hidden information - BUT it removes links TO the WHOLE OF the DOCUMENT - "how to remove the links, ONLY the hidden parts of the document"

    Hidden text is the collection of glyphs in the PDF page using the text rendering mode 3 (no terms, no fill).

    The links set up in connection with this hidden text are not 'hidden' (this isn't how it works with annotations PDF link - see ISO 32000-1: 2008).

    Any link annotation placed in a PDF file are the same as any other annotation link (with the exception, of course, of whatever Action the link happens to).

    Thus, no special sauce for the links that were placed in conjunction with now deleted "no hidden text.

    In the context of what you wrote, maybe it's you select - Ctrl + click the link annotations of interest and press the delete key.

    Be well...

  • Remove the dialog box no longer appears. How can I get the dialog box to delete return? I want to delete the pictures from my hard drive not only lightroom

    I use Lightroom as my main photo organization, so when I want to delete a photo, I want to be able to delete if my hard drive most of the time, I rarely remove photos from catalogs or collections, so having only not the pop-up dialogue box more is a real problem for me.

    Also, what would be a good way to discover photos that has not removed the disc so I can delete them? is it possible that I can synchronize one catalog to another? @

    You try to delete from disk or a Collection?  If the attempt to delete a Collection, it does not work.  You must use the files if you also have the ability to delete from the drive of

Maybe you are looking for

  • Cards SD Tecra 9000

    I can't read all the SD cards, I've tried in the SD slot provided on this laptop. Everything looks OK in Device Manager, showing a TOSHIBA SD Card Controller Type A, which is fully functional. Anyone have any ideas?

  • A computer WinXP SP1 can be updated WinXP SP2 or SP3

    Windows xp service pack 1 recent recharge is no longer compatible with the windows update web site 32 dial the system

  • Apps aren't self-synchronization in my Lenovo a7000 in wifi

    Hi I used this phone 'lenovo A700' en almost 2 weeks. My apps are not automatically sync in this phone in wifi in particular ex.gmail, fb, etc. But in mobile data itz works very well. It occurs oly in my camera or anyone else facing this problem. Do

  • Windows 7 does not accept my password.

    I used Windows 7 Ultimate for a while using the same password.  I did not, don't repeat it, forgot my password, but now it won't accept it.  Why is this happened, and more important still, how do I get back?  I don't have a disc pre-made that will al

  • How to get the HTML of a web page?

    Hello Fisrtly I am a french student, sorry for my bad English level... I have an application that retrieve information about a web site, for this I wish to retrieve an html page in a string, after that, I cut the string to retrieve specific informati