Get multiple Input/Output Stream from same socket ?

For a better express of my problem i will put my test example
I have those 4 classes
package test;
import...
public class ReaderExecutor extends Thread{
        private InputStream in = null;
        private static int defaultID = 0;
        private int ID = getID();
        public ReaderExecutor(InputStream in){
            this.in = in;
        public void run(){
            try {
                int c ;
                while ((c=in.read())!=-1)
                    System.out.println("ReaderThread " + this.ID + ":" + c);
            catch (IOException e) {
                System.out.println("ReaderThread "+this.ID+" stopped !");
        private static int getID(){
            return defaultID++;
package test;
import...
public class WriterExecuter extends Thread{
    OutputStream out = null;
    private static boolean odd = true;
    private boolean isOdd ;
    public WriterExecuter(OutputStream out) {
        this.out = out;
        isOdd = odd;
        odd = !odd;
    public void run(){
        try{
            for (int i = isOdd?1:2;i<10;i+=2){
                System.err.println(i);
                out.write(i);
        }catch(Exception e){
            System.out.println("WriterThread stopped !");
package test;
import...
public class Main { 
    public Main() {
    public static void main(String[] args) throws Exception {
        try{
            ServerSocket ss = new ServerSocket(9090);
            System.out.println("Ascult ... ");
            Socket client = ss.accept();
            new ReaderExecutor(client.getInputStream()).start();
            //Thread.sleep(2000);
            new ReaderExecutor(client.getInputStream()).start();
        }catch (Exception e){
            e.printStackTrace();
package test;
import...
public class Main1 {
    public Main1() {
    public static void main(String[] args) {
        try{
            Socket s = new Socket("localhost",9090);
            WriterExecuter t= null ;
            t = new WriterExecuter(s.getOutputStream());
            t.start();
            t = new WriterExecuter(s.getOutputStream());
            t.start();
        }catch(Exception e){
            e.printStackTrace();
}Now if i run successive Main , Main1 i get this output
Ascult ...
ReaderThread 0:0
ReaderThread 1:0
ReaderThread 0:0
ReaderThread 1:0
ReaderThread 0:0
ReaderThread 1:0
ReaderThread 0:0
ReaderThread 1:0
ReaderThread 0:0
ReaderThread 0 stopped !
ReaderThread 1 stopped !The question is can i get other Input/Output individual streams with a separate logic functionality from the same socket?
From this example it seems i can't :(
Thx
Alex

For what you are trying to do the simplest solution is to have one socket per "stream" that is the way they are designed to be used.
However, you can multiplex multiple stream over a single socket, but you have do the coding yourself or use a solution which does this for you e.g. JMS. (There is no support at the socket level for this)

Similar Messages

  • How to get multiple html output file  from an xml document via xslt?

    Hi,
    the purpose is to generate multiple html output file from one xml file
    depending on special tag.
    exp: i have an xml file which contains sevreral articles so how to get each article section in an independant html file
    Thanks for help

    Not a standard feature of XSLT. But Michael Kay's XSLT implementation, SAXON, provides that as an extension. Get it here:
    http://saxon.sourceforge.net/

  • Row should be locked before getting an output stream from an attribute

    I have table Worker with photo attribute (its database type is ORDSYS.ORDIMAGE, entity attribute type is OrdImageDomain).
    I use standard display and edit renderer for displaying and changing ord-image attribute.
    If I add new worker and set him photo, everything is OK.
    But if I edit some existing worker and set them photo, while posting to database exception is thrown.
    This problem began some time ago, after made some changes (like upgrade JDev, changing some AM configuration properties, and so on...), but I ca't reproduce right behaviour.
    I use JDeveloper 9.0.3.2, database is Oracle8i Release 8.1.6.0.0, I tried reserved and stateful AM mode both (the same bad result), pesimistic locking.
    Error occures inside Tomcat 4.1.27 and OC4J both.
    Does anybody know any hint about this error...?
    Than you very much
    Jan
    PS. Error message datail:
    oracle.jbo.DMLException: JBO-26041: Failed to post data to database during "Update": SQL Statement "JBO-25040: Row should be locked before getting an output stream from an attribute.".
         at oracle.jbo.server.EntityImpl.doDMLWithLOBs(EntityImpl.java:4542)
         at oracle.jbo.server.EntityImpl.doDML(EntityImpl.java:4422)
         at oracle.jbo.server.EntityImpl.postChanges(EntityImpl.java:3544)
         at oracle.jbo.server.DBTransactionImpl.doPostTransactionListeners(DBTransactionImpl.java:2290)
         at oracle.jbo.server.DBTransactionImpl.postChanges(DBTransactionImpl.java:2232)
         at oracle.jbo.server.DBTransactionImpl.commitInternal(DBTransactionImpl.java:1527)
         at oracle.jbo.server.DBTransactionImpl.commit(DBTransactionImpl.java:1693)
         at oracle.jbo.html.jsp.datatags.CommitTag.doStartTag(CommitTag.java:45)
    ## Detail 0 ##
    oracle.jbo.JboException: JBO-25040: Row should be locked before getting an output stream from an attribute.
         at oracle.jbo.domain.BaseLobDomain.getOutputStream(BaseLobDomain.java:729)
         at oracle.ord.im.OrdDomainUtil.loadAndSetProperties(OrdDomainUtil.java:656)
         at oracle.ord.im.OrdImageDomain.saveToDatabase(OrdImageDomain.java:2325)
         at oracle.jbo.server.EntityImpl.doDMLWithLOBs(EntityImpl.java:4521)
         at oracle.jbo.server.EntityImpl.doDML(EntityImpl.java:4422)
         at oracle.jbo.server.EntityImpl.postChanges(EntityImpl.java:3544)
         at oracle.jbo.server.DBTransactionImpl.doPostTransactionListeners(DBTransactionImpl.java:2290)
         at oracle.jbo.server.DBTransactionImpl.postChanges(DBTransactionImpl.java:2232)
         at oracle.jbo.server.DBTransactionImpl.commitInternal(DBTransactionImpl.java:1527)
         at oracle.jbo.server.DBTransactionImpl.commit(DBTransactionImpl.java:1693)
         at oracle.jbo.html.jsp.datatags.CommitTag.doStartTag(CommitTag.java:45)

    Thanks for replay.
    Yes, I use JDev wizard generated BC4J JSP app (it was generated inside 9.0.2 and then migrated to 9.0.3).
    I changed inside it many things, but I thing no important.
    I have for example copying record to history while editing, but when I disable it, the same problem occures.
    I changed database - 8.1.7 to 9.2.0.2.0, but the same problem.
    Any hint?
    Thanks for any comment.

  • Socket input / output stream

    Does anyone know if the input / output streams returned by getInputStream() / getOutputStream() in java.net.Socket are buffered by default?

    y they are buffered, but to use the buffer, you have to use available() and read(byte[] buf ...

  • Parsing input stream from a socket

    Hi, i must read a byte stream from a socket. My problem is that i cannot determine when a stream ends because there are no terminator characters. I tried to use the read() method of BufferedReader class but it blocks when server statement ends. Is there a way to read the stream and answer to the server?
    Thanks,
    Andrea

    andmus wrote:
    Hi, i must read a byte stream from a socket. My problem is that i cannot determine when a stream ends because there are no terminator characters. I tried to use the read() method of BufferedReader class but it blocks when server statement ends. Is there a way to read the stream and answer to the server?
    If you're reading HTTP...
    Unless the request has been sent with Connection: close, it's normal that your read blocks, since the connection is purposefully left open to accomodate further exchanges.
    You'll have to parse the data to know when each message is complete. The first empty line (bytes: \r\n\r\n ASCII) denotes the end of the header. The header will have a Content-Length property which tells you how many bytes are left to read.
    Google the HTTP specs if you don't know them.

  • Sharing an output stream from more than 1 thread.

    I have a problem, an ObjectOutputStream is giving me a nullpointerexception.
    I have a thread which connects to a server application and uses object input/output streams to communicate. This thread will deal with any incoming requests from the server concurrently from the main program. I presumed you could use the same Socket connection that was created in this thread to send objects from other threads (for example the main thread) but I think I presumed wrong.
    This is part of the class which runs as a separate thread:
        public void connect()
            try
                mainSocket = new Socket(hostName, hostPort);
                in = new ObjectInputStream(mainSocket.getInputStream());
                out = new ObjectOutputStream(mainSocket.getOutputStream());
            catch(UnknownHostException e)
                System.out.println(e.getMessage());
            catch(IOException e)
                System.out.println(e.getMessage());
        public void run()
            connect();
            while(true)
             // (Not complete)
        public boolean verifyEmployeeName(String employeeName)
            boolean answer = false;
            try
                out.writeObject(Server.protocol.VERIFY_EMPLOYEE);
                out.writeObject(employeeName);
                answer = in.readBoolean();
            catch(IOException e)
            return answer;
        }The verifyEmployeeName() method is called externally from the main thread and generates the IOException at out.writeObject(Server.protocol.VERIFY_EMPLOYEE); (or the first point at which the socket is used). Anyway my question is; do you have to create a new socket for each thread (bear in mind I haven't yet put in synchronization features) or is this nothing to do with that?
    Very grateful for any help you have to offer.

    alex.p wrote:
    Anyway my question is; do you have to create a new socket for each thread (bear in mind I haven't yet put in synchronization features) Not necessarily. But you'll have to sequentialise the communication.
    Create a communication thread. Give it the control over the socket. Have it expose a BlockingQueue that takes some form of "tasks". As a thread, that communicator polls its queue, and executes the tasks. Other threads post their tasks on the queue and wait until they're completed. Look for clues in the java.util.concurrent package.

  • Buffered input/output stream

    How the buffereing is done in buffered input/output streams?
    From the API doc I got to know that they use internal buffer to store bytes before they can be read or written. But i found that File input/output stream also have methods like read(byte[]) or write(byte[]). So what is extra in buffered input/ouput streams? Does the phrase "buffered" suggests that bytes can be read from an array or be written to an array? Am i thinking the right way?

    How the buffereing is done in buffered input/output
    streams?
    From the API doc I got to know that they use internal
    buffer to store bytes before they can be read or
    written. But i found that File input/output stream
    also have methods like read(byte[]) or write(byte[]).Thouse are your buffer, not the streams'.
    So what is extra in buffered input/ouput streams?
    Does the phrase "buffered" suggests that bytes can be
    read from an array or be written to an array? Am i
    thinking the right way?No. It means that the stream either prefetches some data even if it's not requested yet, or that it withholds data that it's supposed to write until it's flushed or gets a larger chunk.

  • Object input/output stream

    Hi, i'm currently doing a software enginnering project at university. I need to understand how to save and read from files.
    I've been told to look at object input/output stream, which I have, but I can't get my head around what's written in the books. Does anyone know where i can find a good tutorial on this subject?
    thanks
    AK

    I like the tutorial on this site because it tells you what to use for what you're doing (click on Using the Streams). Hope it helps!
    http://java.sun.com/docs/books/tutorial/essential/io/index.html

  • Multiple POu2019s were created from same requirement

    Issue: multiple POu2019s were created from same requirement (i.e. requirement had quantity of 100.  60 was put on one PO and 40 was put on another PO), BBP_GET_STATUS_2 program returns an error
    -Please let me know some tips/ pointers to investgate this issue.
    -How to investgate this issue? I really appreciate a thought process to investigate,

    Hi Rick,
    The splitting of a requirement into mulitple PO's will happen due to some criteria checks. Please see my note 1380879, where it states the following:
    There are a number of criteria that are taken into account when creating    
    the follow-on document:                                                                               
    proc_org    Purchasing Org                                                  
    proc_group    Purchasing Group                                              
    co_code     Company Code                                                    
    Pcins       Procurement card company                                        
    Pcnum       Procurement card number                                         
    ext_quote_id  External Quotation                                            
    logsys_fi     Logical Financial System                                      
    ext_dem_logsys  Logical System from where an External Re-quirement Comes                                                                               
    ext_dem_posid External Requirement Item Number                              
    Subtype     Item Subtype (Extended, local scenario)                         
    guid_ven    Vendor Guid                                                     
    guid_prpven   Desired vendor Guid                                           
    suppl_addr.   Ship to address fields                                        
    Doc_type    Process Type                                                                               
    Additional splits:                                                          
    Always split extended limit items                                           
    Always split if there is a missing vendor                                   
    Items grouped by hierarchies are split to separate PO s                                                                               
    The split criteria can be found within the code of Class                    
    CL_BBP_SC_TRANSFER. From this class there are a method's depending on       
    the follow-on document type:                                                                               
    SPLIT_BACKEND_OBJECTS                                                       
    SPLIT_BACKEND_PO                                                            
    SPLIT_BID                                                                   
    SPLIT_LOCAL_AND_BACKEND_ITEMS                                               
    SPLIT_LOCAL_OBJECTS                                                         
    SPLIT_LOCAL_PO                                                              
    SPLIT_LOCAL_PO_DO                                                           
    SPLIT_PO_BE_MAP_CRITERIA                                                    
    SPLIT_PO_LOC_CHK_LIMIT                                                      
    SPLIT_PO_LOC_CMP_CRITERIA                                                   
    SPLIT_PO_LOC_MAP_CRITERIA                                                   
    SPLIT_REQUISITION                                                           
    SPLIT_RESERVATION   
    So if all of the above criteria are the same then one PO should have been created but if the above critieria is different in each item then the system will split the items into different PO's
    I hope this helps
    Kind Regards,
    Lisa

  • Question about creating multiple output  files from same query

    I have a query like this:
    select * from emp;
    ename empno deptno
    Scott 10001 10
    Tiger 10002 10
    Hanson 10003 20
    Jason 10004 30
    I need to create multiple output files in xml format for each dept
    example:
    emp_dept_10.xml
    emp_dept_20.xml
    emp_dept_30.xml
    each file will have the information for employees in different departmemts.
    The reason I need to do this is to avoid executing the same query 200 times for generating the same output for different departments. Please let me know if it is practically possible to do this.
    Any input is greatly appreciated.
    Thanks a lot!!

    You can write a shell script to generate the multiple spools files for the same output. Below script may helps you.
    #====================
    #!/bin/bash
    n=0
    while [ $n -le 20 ]
    do
    n=`expr $n + 1`
    sqlplus -s system/manager <<EOF
    spool emp_dept_$n.xml
    select count(1) from tab;
    spool off
    EOF
    done
    #====================

  • I get an input/output error when i try to restore a functioning backup from my external harddrive to my new internal harddrive through disk utility?

    my hardrive Had a smart status warning so i made a backup of it on my external harddrive through disk utility. i checked to make sure that the backup was working and i had no problems with it. i then bought a new internal harddrive and swaped it out but when i was in recovery mode to try to restore my new hardrive i kept getting an error message saying restore error, input/output error

    The big dilemma with a new Internal drive is separating Drive operation from 'inside the MacBook' operation. If you had an External Enclosure, you could do all the work (including booting up from the new drive) using the External enclosure.
    Then if a know-good drive develops problems only when moved inside the MacBook, it is time to try a replacement cable.

  • How to get server data without reading from the socket stream?

    My socket client checks for server messages through
                while (isRunning) { //listen for server events
                    try {
                            Object o = readObject(socket); //wait for server message
                                tellListeners(socket, o);
                    } catch (Exception e) {
                        System.err.println("ERROR SocketClient: "+e);
                        e.printStackTrace();
                    try { sleep(1000); } catch (InterruptedException ie) { /* ignore */ }
                }//next client connectionwith readObject() being
        public Object readObject(Socket socket) throws ClassNotFoundException, IOException {
            Object result = null;
    System.out.println("readObject("+socket+") ...");
            if (socket != null && socket.isConnected()) {
    //            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                ObjectInputStream ois = new ObjectInputStream(new DataInputStream(socket.getInputStream()));
                try {
                    result = ois.readObject();
                } finally {
    //                socket.shutdownInput(); //closing of ois also closes socket!
        //            try { ois.close(); } catch (IOException ioe) { /* ignore */ }
            return result;
        }//readObject()Why does ois.readObject() block? I get problems with this as the main while loop (above) calls readObject() as it's the only way to get server messages. But if i want to implement a synchronous call in adition to this asynchronous architecture (call listeners), the readObject() call of the synchronous method comes to late as readObject() call of the main loop got called before and therefore also gets the result of the (later) synchronous call.
    I tried fideling around with some state variables, but that's ugly and probably not thread safe. I'm looking for another solution to check messages from the server without reading data from the stream. is this possible?

    A quick fix:
    - Add a response code at the beginning of each message returned from the server indicating if the message is a synchronous response or a callback (asynch);
    - Read all messages returned from the server in one thread and copy callback messages in a calback message queue and the synch responses in an synch responses queue;
    - Modify your synchronous invocation to retrieve the response from the responses queue instead from the socket. Read the callback messages from the corresponding queue instead from the socket.
    Also take a look at my website. I'm implementing an upgraded version of this idea.
    Catalin Merfu
    High Performance Java Networking
    http://www.accendia.com

  • How do I get multiple inputs?

    Hi. I have Logic Pro 9 installed on my Macbook and on my iMac. I have tried to use a 12 channel mixing desk as the inputs for recording, but it will only ever allow me to select 2 inputs. This is on my Macbook only, I don't have the same problem on my iMac.  Previously I have a 2 input device (an Apogee Duet) and used this on both computers. When I connect the mixing desk (Yamaha MG166cx-usb via the firewire to USB connector, it shows up in the preferences and allows me to select it as the input and output device under preferences, audio, devices, core audio option. If I add a new audio track, it will only still show me the option of selecting input 1 or input 2. If I do the same on my iMac, it will show multiple inputs. I have uninstalled my previous audio device, and also uninstalled Logic, moved to trash, downloaded again, but the same symptoms are there.

    Yes. Of course I read the manual. It quite clearly shows in Cubase, which I haven't installed and don't use 4 stereo and 8 monoaural tracks. It's on page 11 of the hard copy manual. I have however just set up a blank project and tried recording from different channels on the mixer. (1 and 5). I can record either one individually, but only two channels simulaneously, but no more than two channels it seems. Are you saying this is all I ever will achieve with this desk? Seems a bit pointless almost to sell a desk with multiple channels yet only lets you record two of them with one of it's selling points - a USB connection facility. It's not the reason I bought the desk by the way, I use an Apogee Duet to record at home, I just wanted to be able to set up and record each individual channel during a live performance via the PA and then clean up and mix properly at home. Guess I'm not going to get far on that front

  • SOLVED: Getting an Input/Output error when accessing certain files

    My system started failing a few days ago because of sudden Input/Output errors when trying to access certain files. It was running fine until various applications started crashing like for example Pidgin (in retrospect probably because of DBus crashing). I decided to reboot and now can't login anymore because the DBus module fails to load which in turn means that HAL doesn't load either and so I can't use my keyboard to login.
    The error message I get from DBus is that it can't access the file /etc/dbus-1/system.d/org.freedesktop.PolicyKit.conf because of an Input/Output error. I tried to fix/see what was wrong using the arch livecd. Because I thought my problem had to do with a pacman update that had failed before I'd rebooted, I updated my system and I noticed that when pacman tried to access other files it came back with the same error message. The files seemed pretty random, one of them was fakeroot.conf and then several library files like libfaad (sorry this is kind of vague but I'm away from home right now and can't go online very often so I'm writing this from memory).
    I'm guessing its a hard drive problem because checking the filesystem for errors came back with nothing. I was just wondering whether anyone had any other ideas before I go and reinstall. I'm going back home tomorrow so I'll be able to follow any advice/reinstall then.
    Last edited by siell (2010-04-08 17:01:37)

    UPDATE
    It seems to be fixed! The second run of e2fsck fixed some more issues and the files that were causing the problems earlier seemed to have bad inodes. Boots fine now and I can get into my system. I checked and I still have a reasonable amount of free space so I don't think that was the reason ... I have no idea how the filesystem got so corrupted out of nowhere.
    A few things are different, for example, it asked me to unlock the keyring and I couldn't mount my external encrypted drive anymore and had to do it manually with cryptsetup. e2fsck made quite a few changes so I imagine it's due to that. Shouldn't be to hard to fix though.
    Thanks for your help!

  • Wscompile stubbornly uses SOAPElement as input/output to/from operation.

    Hello. I am trying to create a web service client to consume our own web service using JWSDP 1.6. I have modified webserviceclient.xml to add "features=searchschema" in the wscompile element.
    That correctly creates proxy classes for all the complexTypes in our web service's schema. However, our operation called runTransaction() should be accepting an object of type RequestMessage and returning an object of type ResponseMessage. The code generated by wscompile accepts and returns SOAPElement instead.
    I have blindly tried all sorts of combinations of features (e.g. unwrap, explicitcontext) when calling wscompile but to no avail.
    Am I missing something? When and why would wscompile not use the correct classes as input/output for any given operation? When and why would it choose SOAPElement instead?
    In its current state, the generated code would let me populate the RequestMessage object with data but I do not see how I can eventually pass this RequestMessage object to the runTransaction() method (unless maybe I use serialization or something but that seems unnecessarily complicated). So, the generated proxy classes seem useless at this point.
    Thanks. I'd really appreciate any help/direction.

    Hello. I went ahead and added resolver.jar file to my classpath. Then, it looked for XMLStreamException, which I found in sjsxp/lib/jsr173_api.jar (which I have yet to find out what it's for). I went ahead and added that too. And now, I'm getting the stack trace below.
    1. Why is it looking for a class from BEA?
    2. How do I make it not to?
    Please note that I do not have any configuration file or anything. Is there some client-side deployment file that I need to have and configure?
    Thanks again,
    Ever
    Exception in thread "main" javax.xml.stream.FactoryConfigurationError: Provider com.bea.xml.stream.MXParserFactory not found
    at javax.xml.stream.FactoryFinder.newInstance(FactoryFinder.java:72)
    at javax.xml.stream.FactoryFinder.find(FactoryFinder.java:176)
    at javax.xml.stream.FactoryFinder.find(FactoryFinder.java:92)
    at javax.xml.stream.XMLInputFactory.newInstance(XMLInputFactory.java:136)
    at com.sun.xml.ws.streaming.XMLStreamReaderFactory.<clinit>(XMLStreamReaderFactory.java:63)
    at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.createReader(RuntimeWSDLParser.java:140)
    at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.parseWSDL(RuntimeWSDLParser.java:165)
    at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:62)
    at com.sun.xml.ws.wsdl.WSDLContext.<init>(WSDLContext.java:57)
    at com.sun.xml.ws.client.ServiceContextBuilder.build(ServiceContextBuilder.java:77)
    at com.sun.xml.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java
    :117)
    at com.sun.xml.ws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:50)
    at javax.xml.ws.Service.<init>(Service.java:58)
    at com.mycompany.client.soap.TransactionProcessor.<init>(TransactionProcessor.java:42)
    at MySample.main(MySample.java:141)

Maybe you are looking for

  • How to write good PHP code in dreamweaver?

    Here's the thing.  I'm using Dreamweaver CS4 to develop a website.  In the past my php files would look like this: <?php     echo '<h1>Welcome ' . $name . '</h1>'; ?> This caused problems in the design view because all I would see would be the php ic

  • Aperture 3.0 Library corrupt?! What to do

    I have a serious problem! Aperture 3.0 crashes whenever i try to open my Library; but also when i try one of the 3 repair options! A fresh library works without any problems. Before installing A3 today, I was exporting all the projects. Installed A3,

  • Can't get rid of the JTable's white column divider

    I want a JTable that has no grid lines and no space between cells, with or with out headers. Basicly all cells should butt against each other with no grid lines. So far I have succeeded with this, with a exception to some white divider that is about

  • Unable to update to OS 6.0 Bundle 2647 either wirelessly or via Desktop Software for Mac

    I have a BB Torch 9800 and I've tried all I know to update the system software on my BB wirelessly but it gives me the message "Update cannot continue, Update using BB Desktop Manager on your computer". So I plugged my BB in but it doesn't give me a

  • Podcast Sync w/ iPhone

    I am having an interesting Issue with Syncing my iPhone with iTunes. It is automatically copying ALL podcasts no matter what my setting is in the Podcasts tab of the sync section of iTunes. I have tried disabling syncing of podcasts, changing the set