Using Sockets with BufferedInputStream

Hi,
Many thanks in advance for any help or advice. I have been struggling with this for a while now.
I have data comming in from a Socket. I create a BufferedInputStream like this:
inputStream = new BufferedInputStream( socket.getInputStream() ); The class that this code is in extends Thread, and in the run method i have:
while( true )
               try
                    inputSource = new InputSource( inputStream );
                    responseXML.parseClientData( inputSource, client.getID() );
               catch( Exception e )
                    System.out.println( "run.Error: " + e );
          }The class responseXML takes the stream and tries to parse the XML as follows:
public void parseClientData( InputSource dataFromFlash, int clientID )
          System.out.println( "parseClientData" + clientID );
          try
               xmlReader.parse( dataFromFlash );
          catch( Exception e )
               System.out.println( "parseClientData.Error: " + e );
My problem:
The above method (parseClientData) is getting called over and over again - it is stuck in an infinite loop.
And this error is caught in the above methodt:
parseClientData.Error: java.io.IOException: Stream closed
Any ideas? I have been struggling with this for far too long.
I thnik it might be to do with blocking and non-blocking input streams.
When i used a noraml BufferedReader - i didn't have this problem.
Thanks.
Regards, Custom
Message was edited by:
custom
Message was edited by:
custom

Come on buddy wake up!
You have a while loop that NEVER exits and exception blocks that don't do anything productive and this error message "ClientData.Error: java.io.IOException: Stream closed" tells you exactly what the problem is.
Do you think maybe you should exit the while loop if an exception is thrown? Do you? Perhaps? Maybe?

Similar Messages

  • Using sockets with java from PL/SQL in Oracle 8.1.7 DBA

    Hey all,
    I've been struggling for a couple of weeks now with a problem. I wrote a framework around a toolkit which makes socket connections to another server. I am attempting to use the framework from within a PL/SQL script, which is calling the framework class files which have been loaded into Oracle 8.1.7 database. The problem seems to be if I grant all permissions, or socket permissions for all hosts/ports, or even the ones I know about are being used, I get a hang when trying to connect. The funny thing is, using the toolkit, if I invoke their classes directly within code written from Oracle's code editor, it will work.
    I suspect there is
    a) Some hidden permission issue
    b) A bug in the sockets implementation Oracle is using for their JVM.
    Can anyone offer insight to this problem?
    Thanks,
    Dave Blake
    [email protected]

    Hello,
    I'm trying to investigate the same thing.
    I want to make a soap-client with PL/SQL with 8i 8.1.6.0.0
    Did you succeed some additional information ??
    I tried to run the following example:
    http://www.oracle.com/technology/tech/webservices/htdocs/samples/dbwebservice/DBWebServices_PLSQL.html
    but it only works with 9i.
    With 8i the errors encountered were : XMLTYPE undefined
    Perhaps if we find the definition of XMLTYPE and we process it to 8i we'll be able to run the example ??
    thank's

  • Using sockets with Applet

    Hey,
    I have a website which has an applet on one of the pages. I put in code that uses a socket to connect to MY computer. ( i want to use my computer as a server which stores data/accounts/etc) A SecurityException was thrown when I tested the applet. Is what I'm trying to do possible? or does something like this have to connect to a server which is on my website?
    Thanks

    I believe you can run something like this by signing the applet.
    And then the user has the option of allowing or disallowing a signed applet to do that kind of thing. I don't know which is the default.

  • Communication between Windows 7 and Windows 8(and above) using Sockets(TCP and UDP)

    I need to use TCP and UDP using Sockets to communicate between two(or more) applications installed in Windows 7 and Windows 8.
    Is it possible.? I tried within a LAN, but in vain. If needed I would post the appropriate code.
    Note: I only tried running exe(s) in these machines and not with installation.

    Hello Prabodh.Minz,
    >>Is it possible.?
    It is not clear what develop language you are using, here are examples which uses the C# based on .NET. It created the communition between two machines by using sockets with TCP protocol, a server and a client:
    Synchronous example:
    Client and
    Server.
    Asynchronous example:
    Client and
    Server.
    Multi-client per one server - socket programming in .net(C#)
    >>Note: I only tried running exe(s) in these machines and not with installation.
    There are all .exe.
    Regards.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to use a Socket with an IP adress.

    Hi,
    I have made a simple client/server app using sockets and streams. I can make a ServerSocket on a port and then connect a client using the following Socket constructor:
    Socket(hostname, port)
    This works fine when I know the computer name I am connecting to, but what if I want to connect to a remote computer using an IP address of the form 127.0.0.1 (obviously not this address if the computer is remote) and a port number ?
    I have found the InetAddress class but I don't think I can use this class to represent/format a local remote address and Socket contructors want a InetAddress to specify an IP adress.
    Any help would be appreciated.

    Actually InetAddress constructor is hidden andcan't
    be used in anyway that I know.You're right. My mistake. Um, that can't be true. InetAddress (JDK 1.5) is a public class with static constructors based on the return of a method.
    InetAddress address = InetAddress.getByName("127.0.0.1");
    or
    InetAddress address = InetAddress.getByName("localhost");
    These will return an InetAddress object which may then be used in the socket constructor.
    Socket socket = new Socket(address, int portNumber);

  • How to use setSoTimeOut() with socket ??

    HI All!
    I eagerly need to know how to use setSoTimeOut() with socket (on server side).
    Actually the scenario is that My Server accepts connection and waits for connected client to send data to it. I WANT TO KEEP, IF CLIENT DOENS'T SENDS ANY DATA TO SERVER WITHIN 5 min. THEN SERVER MUST CLOSE THE CONNECTION, BUT IF SERVER RECEIVES STILL A BYTE FROM THE CLIENT WITHIN 5 mins., THE SERVER MUST RESET CHECKING TIME OUT FOR NEXT 5 MINUTES.
    How can i do that??
    Any help with example will be appreciated!!
    Thanx in advance

    you'd have to do something like this:
    (this is all assuming you want to read Strings from the socket. setSoTimeout works for any read() call to the InputStream associated with the Socket)
    ServerSocket ss = new ServerSocket(myPort);
    Socket s = ss.accept();
    s.setSoTimeout(5*60*1000); // 5 mins * 60 secs * 1000ms
    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    boolean running = true;
    while(running)
    try
    String readIn = in.readLine();
    // do whatever you want with the data read
    catch(SocketTimeoutException)
    running = false;
    Now. That's what I think needs to be done. I don't have Java on the machine I'm currently on, so I can't test/verify it, but it goes something like that.
    Good luck,
    Radish21

  • How use multithead with socket

    How use multithead with socket
    I need do a client and server program that accept multitherad issue
    Thanks who can help me

    you'd have to do something like this:
    (this is all assuming you want to read Strings from the socket. setSoTimeout works for any read() call to the InputStream associated with the Socket)
    ServerSocket ss = new ServerSocket(myPort);
    Socket s = ss.accept();
    s.setSoTimeout(5*60*1000); // 5 mins * 60 secs * 1000ms
    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    boolean running = true;
    while(running)
    try
    String readIn = in.readLine();
    // do whatever you want with the data read
    catch(SocketTimeoutException)
    running = false;
    Now. That's what I think needs to be done. I don't have Java on the machine I'm currently on, so I can't test/verify it, but it goes something like that.
    Good luck,
    Radish21

  • Send html page (with images) using sockets

    I am trying to implement http and am coding this using sockets. So it is a simple client-server set up where the browser queries my server for a webpage and it should be shown. The html itself is fine, but I can't get any of the images to show up! All of my messages give me a status "200 OK" for the images, so I cant understand what my problem is!
    Also, is the status and header lines supposed to be shown in the browser? I didnt think so but it keeps showing up when I query a webpage.
    Please help!
    import java.io.* ;
    import java.net.* ;
    import java.util.* ;
    public final class WebServer
         public static void main(String argv[]) throws Exception
              // Set the port number.
              int port = 8888;
              // Establish the listen socket.
              ServerSocket ssocket = new ServerSocket(port);
              // Establish client socket
              Socket csocket = null;
              // Process HTTP service requests in an infinite loop.
              while (true)
                   // Listen for a TCP connection request.
                   // (note: this blocks until connection is made)
                   csocket = ssocket.accept();     
                   // Construct an object to process the HTTP request message.
                   HttpRequest request = new HttpRequest(csocket);
                   // Create a new thread to process the request.
                   Thread thread = new Thread(request);
                   // Start the thread.
                   thread.start();
    final class HttpRequest implements Runnable
         final static String CRLF = "\r\n";
         Socket socket;
         // Constructor
         public HttpRequest(Socket socket) throws Exception
              this.socket = socket;
         // Implement the run() method of the Runnable interface.
         public void run()
              try
                   processRequest();
              catch (Exception e)
                   System.out.println(e);
         private static void sendBytes(FileInputStream fis, OutputStream os)
         throws Exception
            // Construct a 1K buffer to hold bytes on their way to the socket.
            byte[] buffer = new byte[1024];
            int bytes = 0;
           // Copy requested file into the socket's output stream.
           while((bytes = fis.read(buffer)) != -1 ) {
              os.write(buffer, 0, bytes);
              os.flush();
         private static String contentType(String fileName)
              fileName = fileName.toLowerCase();
              if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
                   return "text/html";
              if(fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") ) {
                   return "image/jpeg";
              if(fileName.endsWith(".gif")) {
                   return "image/gif";
              return "application/octet-stream";
         private void processRequest() throws Exception
              // Get a reference to the socket's input and output streams.
              InputStream is = socket.getInputStream();
              DataOutputStream os = new DataOutputStream(socket.getOutputStream());
              // Set up input stream filters.
              InputStreamReader ir = new InputStreamReader(is);
              BufferedReader br = new BufferedReader(ir);
              // Get the request line of the HTTP request message.
              String requestLine = br.readLine();
              // Display the request line.
              System.out.println();
              System.out.println(requestLine);
              // Get and display the header lines.
              String headerLine = null;
              while ((headerLine = br.readLine()).length() != 0)
                   System.out.println(headerLine);
              // Extract the filename from the request line.
              StringTokenizer tokens = new StringTokenizer(requestLine);
              tokens.nextToken();  // skip over the method, which should be "GET"
              String fileName = tokens.nextToken();
              // Prepend a "." so that file request is within the current directory.
              fileName = "C:\\CSM\\Networking\\Project1" + fileName;
              // Open the requested file.
              FileInputStream fis = null;
              boolean fileExists = true;
              try {
                   fis = new FileInputStream(fileName);
              } catch (FileNotFoundException e) {
              fileExists = false;
              // Construct the response message.
              String statusLine = null;
              String contentTypeLine = null;
              String entityBody = null;
              if (fileExists) {
              statusLine = "200 OK" + CRLF;
              contentTypeLine = "Content-type: " +
                   contentType( fileName ) + CRLF
                   + "Content-length: " + fis.available() + CRLF;
              else {
              statusLine = "404 Not Found" + CRLF;
              contentTypeLine = "Content-type: text/html" + CRLF;
              entityBody = "<HTML>" +
                   "<HEAD><TITLE>Not Found</TITLE></HEAD>" +
                   "<BODY>Not Found</BODY></HTML>";
              // Send the status line.
              os.writeBytes(statusLine);
              System.out.println(statusLine);
              // Send the content type line.
              os.writeBytes(contentTypeLine);
              System.out.println(contentTypeLine);
              // Send a blank line to indicate the end of the header lines.
              os.writeBytes(CRLF);
              // Send the entity body.
              if (fileExists)     
                   sendBytes(fis, os);
                   fis.close();
              // file does not exist
                     else
                   os.writeBytes(entityBody);
              // Close streams and socket.
              os.flush();
              os.close();
              br.close();
              socket.close();
    }

    ok. i figured it out. STUPID mistake. i forgot to include "HTTP/1.1" in my status line!!!

  • How can i work with Mysql using socket

    hi
    When i connect through mysql using socket
    then can i send a query to mysql through socket.
    if yes then how
    retrive data which is performed by query
    plz help me
    THANKS

    not like its not possible, but you better refer to JDBC instead of plain socket... its much easier and its already been done...
    google for mysql jdbc tutorial or something...

  • Sending file using sockets (difficult)

    Hi, i have the following section of code
    (of which i am not claiming ownership) which
    implements a DCC Send command from irc.
    It accomplishes this using sockets, and while
    i understand how the code accomplishes what it
    does, i need help with a possible modification.
    Basically what i am looking to do is keep track
    of the progress of the send - so that the
    user can at any time see how much of the file
    has been sent and how much is remaining.
    If anyone has done such a thing in the past or
    has a good idea as to how this should be implemented,
    i would be greatful for their help.
    Here is the code:
    new Thread() {
                public void run() {
                    try {
                        ServerSocket ss = new ServerSocket(0);
                        ss.setSoTimeout(timeout);
                        int port = ss.getLocalPort();
                        //byte[] ip = ss.getInetAddress().getAddress();
                        byte[] ip = InetAddress.getLocalHost().getAddress();
                        long ipNum = 0;
                        long multiplier = 1;
                        for (int i = 3; i >= 0; i--) {
                            int byteVal = (ip[i] + 256) % 256;
                            ipNum += byteVal*multiplier;
                            multiplier *= 256;
                        // Rename the filename so it has no whitespace in it when we send it.
                        // .... I really should do this a bit more nicely at some point ....
                        String safeFilename = file.getName().replace(' ', '_');
                        safeFilename = safeFilename.replace('\t', '_');
                        // Send the message to the user, telling them where to connect to in order to get the file.
                        sendCTCPCommand(nick, "DCC SEND " + safeFilename + " " + ipNum + " " + port + " " + file.length());
                        // The client may now connect to us and download the file.
                        Socket socket = ss.accept();
                        socket.setSoTimeout(30000);
                        // Might as well close the server socket now; it's finished with.
                        ss.close();
                        BufferedOutputStream output = new BufferedOutputStream(socket.getOutputStream());
                        BufferedInputStream input = new BufferedInputStream(socket.getInputStream());
                        BufferedInputStream finput = new BufferedInputStream(new FileInputStream(file));
                        byte[] outBuffer = new byte[bufferSize];
                        byte[] inBuffer = new byte[4];
                        int bytesRead = 0;
                        while ((bytesRead = finput.read(outBuffer, 0, outBuffer.length)) != -1) {
                            output.write(outBuffer, 0, bytesRead);
                            output.flush();
                            input.read(inBuffer, 0, inBuffer.length);
                        output.close();
                        input.close();
                        log("+++ DCC SEND Completed to " + nick + " (" + file.getPath() + ")");
                    }

    You already have the necessary code to find the number of bytes sent at any point during the transmission. You can find out the size of the file by instantiating a RandomAccessFile before you send it, and querying for the file length.
    I suggest you make the file size and bytes sent volatile and conveniently accessible to another thread (best implemented here as an inner class?). Your new thread will need to monitor the file transfer at intervals to update the progress indicator. You can generate estimates of time remaining by measuring the average transmission rate, and extrapolating using the total file size. Classically this is done using an average, but you might be better just maintaining a list of fairly recent samples, allowing for the speed swings inherent in internet connections.
    How you update the progress indicator from your monitor thread is up to you. I suggest exposing methods in the UI for setting the progress and time remaining, and simply update them from the monitor.
    Does this help any?

  • Networking Using Socket

    Hi,
    My team have developed a real-time remote network monitoring system. It consists of server and agent. What the agent does is send the network traffic data to server every one second by using socket. Each second we send the data to the same socket and yes we already make sure that the socket and streams used are closed after data being sent. However I still see a lot of SocketException once in a while whenever the agent tries to send the data.
    1. How can I solve this error ?
    2. Is it possible that I connect to my server just once without closing the connection and still able to send the data every second ?
    Thank you for your time.
    Regards,
    Mustafa
    Below is the code, called every one second :
          * This method sends itself into the server using compressed input/output
          * stream and then will receive back the instance of "replied" CRequest and
          * then further returns it.
          * @return CRequest
         public CRequest sendRequest() {
              SSLSocket server = null;
              GZIPOutputStream gos = null;
              ObjectOutputStream out = null;
              BufferedOutputStream bos = null;
              GZIPInputStream gis = null;
              ObjectInputStream in = null;
              try {
                   SSLSocketFactory sslFact = (SSLSocketFactory) SSLSocketFactory
                             .getDefault();
                   server = (SSLSocket) sslFact.createSocket(hostname, port);
                   String set[] = new String[] { "SSL_RSA_WITH_NULL_MD5" };
                   server.setEnabledCipherSuites(set);
                   server.setReceiveBufferSize(48000);
                   server.setSendBufferSize(48000);
                   if (milisecTimeout != 0) {
                        server.setSoTimeout(milisecTimeout);
                   gos = new GZIPOutputStream(server.getOutputStream());
                   bos = new BufferedOutputStream(gos, 48000);
                   out = new ObjectOutputStream(bos);
                   // /* Can we actually send ourselves and then receive ourselves?*/
                   out.writeObject(this);
                   out.flush();
                   bos.flush();
                   gos.finish();
                   gis = new GZIPInputStream(server.getInputStream());
                   in = new ObjectInputStream(new BufferedInputStream(gis, 48000));
                   /* Returning the newly modified request with results */
                   return (CRequest) in.readObject();
              } catch (Exception e) {
                   System.out.println("trouble sending request" + e);
              } finally {
                   if (gos != null) {
                        try {
                             gos.close();
                             // System.out.println("GOS closed..");
                        } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                        gos = null;
                   if (out != null) {
                        try {
                             out.close();
                             // System.out.println("OUT closed..");
                        } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                        out = null;
                   if (gis != null) {
                        try {
                             gis.close();
                             // System.out.println("GIS closed..");
                        } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                        gis = null;
                   if (in != null) {
                        try {
                             in.close();
                             // System.out.println("IN closed..");
                        } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                        in = null;
                   if (server != null) {
                        try {
                             server.close();
                        } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                        server = null;
                   System.gc();
              return null;
         }

    I've been trying to modify my sendRequest function, so that It will only open and close the connection ONCE. As long as the connection is open I need to be able to send some data to the server. However I've been getting errors and stuffs like that.
    Exception:
    java.io.NotSerializableException: java.io.BufferedOutputStream
    +     at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1081)+
    +     at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1375)+
    +     at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1347)+
    +     at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1290)+
    +     at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1079)+
    +     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:302)+
    +     at com.inetmon.jn.commobj.CRequest.sendRealTimeRequest(CRequest.java:385)+
    +     at com.inetmon.jn.core.internal.CaptureEngine.sendDataBackToServer(CaptureEngine.java:1420)+
    +     at com.inetmon.jn.core.internal.CaptureEngine$4.actionPerformed(CaptureEngine.java:2384)+
    +     at javax.swing.Timer.fireActionPerformed(Timer.java:271)+
    +     at javax.swing.Timer$DoPostEvent.run(Timer.java:201)+
    +     at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)+
    +     at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)+
    +     at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)+
    +     at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)+
    +     at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)+
    received is null
    +     at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)+
    +     at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)+
    The constructor which only be called once.
    public CRequest(Cookie cookie, int id, Object information, String hostname,
                   int port) {
              this.cookie = cookie;
              this.type = RequestConstants.AGENT_SEND_REALTIME_DATA;
              this.id = id;
              this.information = information;
              this.hostname = hostname;
              this.port = port;
              try {
                   SSLSocketFactory sslFact = (SSLSocketFactory) SSLSocketFactory
                             .getDefault();
                   server = (SSLSocket) sslFact.createSocket(hostname, port);
                   String set[] = new String[] { "SSL_RSA_WITH_NULL_MD5" };
                   server.setEnabledCipherSuites(set);
                   server.setReceiveBufferSize(48000);
                   server.setSendBufferSize(48000);
                   if (milisecTimeout != 0) {
                        server.setSoTimeout(milisecTimeout);
                   gos = new GZIPOutputStream(server.getOutputStream());
                   bos = new BufferedOutputStream(gos, 48000);
                   out = new ObjectOutputStream(bos);
              } catch (Exception e) {
                   System.out.println("trouble creating socket" + e);
         }The send request, which sends data whenever I want.
         public CRequest sendRealTimeRequest() {
              try {
                   // gos = new GZIPOutputStream(server.getOutputStream());
                   // bos = new BufferedOutputStream(gos, 48000);
                   // out = new ObjectOutputStream(bos);
                   // /* Can we actually send ourselves and then receive ourselves?*/
                   out.writeObject(this);
                   // out.flush();
                   // bos.flush();
                   // gos.finish();
                   gis = new GZIPInputStream(server.getInputStream());
                   in = new ObjectInputStream(new BufferedInputStream(gis, 48000));
                   /* Returning the newly modified request with results */
                   System.out.println("managed to send once");
                   return (CRequest) in.readObject();
              } catch (Exception e) {
                   e.printStackTrace();
              return null;
         }

  • Using sockets to relay video stream

    Hi there,
    I've been working with java for 4 years now, and I never had troubles making the applications I wanted with it...since my last project :(
    I hope you, gurus from the java community forum, can help me sort this out, but let me explain it to you:
    I'd like to stream video content (let's say from a webcam) to several spectators. But my upload bandwidth (ADSL line) is limited to 512kbps, which is far from enough to send a video streaming (with a bitrate of ~400kbps) to 10 or more viewers.
    That's why I decided to rent a distant server (with a bandwidth of 5Mbps download/upload), and make a java application run on it, which would be able to broadcast the stream to all the viewers.
    So my computer (connected to adsl) captures the video from the webcam, sends it via socket to the rented server, which broadcasts the video to all the spectators. If no video is sent to the rented server, then it should broadcast local files to the spectators.
    Here is a schema of the project so you understand easily (my english is not as good as I'd like it to be, so you may not understand with words only):
    http://www.bf-stream.com/schema1.gif
    My application runs quite well with 5 spectators, but as soon as more viewers come to see the video, it starts hanging, and all the viewers suffer lags and buffering, which is not exactly what I expected...
    Of course, I checked the administration interface on the rented server to see if this was due to a cpu/ram/bandwitdh problem. With no success: with 10 viewers connected, the app uses less than 1% of the cpu power, something like 200kb of RAM, and a bandwidth of 3-4Mbps (which is still under the actual bandwidth capacity of the server).
    That's why I came to the conclusion that my java app was not as good as I thought, and decided to show it to you, so you can help me make it better.
    So here is a schema showing the classes and their interactions:
    http://www.bf-stream.com/schema2.gif
    And here are the sources of the classes:
    StreamRelay.java:
    package com.RR4;
    import java.net.Socket;
    import java.util.Vector;
    import java.util.Observable;
    import java.util.Observer;
    * StreamRelay:
    *  Main class controlling every aspects of the stream
    *  (live content, or files read from hard disk)
    public class StreamRelay extends Observable implements Observer  {
         static public String VERSION = "0.5";
         static public int BUFFER_SIZE = 16;
         private StreamServer streamServer;
         private LiveServer liveServer;
         LocalFile localFile;
         Vector clients;
         boolean streamFromSocket;
         public StreamRelay(int livePort, int relayPort) {
              streamFromSocket = false;
              // clients: vector containing every StreamClient connected
              clients = new Vector();
              // localFile: class reading local files when no live is sent to the relay
              localFile = new LocalFile(this);
              new Thread(localFile).start();
              // streamServer: server listening for new StreamClient
              streamServer = new StreamServer(this, relayPort);
              new Thread(streamServer).start();
              // liveServer: server listening for new sources for live content
              liveServer = new LiveServer(this, livePort);
              new Thread(liveServer).start();
         * addClient: adds new StreamClient to 'clients' vector (a StreamClient is a 'spectator')
         public void addClient(Socket clientSocket) {
             StreamClient client = new StreamClient(this, clientSocket);
         * removeClient: removes a StreamClient from 'clients' vector
         public void removeClient(int index) {
              clients.remove(index);
         * update: updates every StreamClient (which are all Observers of StreamRelay)
         public void update(Observable observable, Object obj) {
              if ((observable.getClass().toString().indexOf("LocalFile")!=-1&&!streamFromSocket)||(observable.getClass().toString().indexOf("LiveStream")!=-1)) {
                   this.notifyObservers( (byte[]) obj);
                   this.setChanged();
         public static void main(String[] args) {
              new StreamRelay(8000, 8080);
    LocalFile.java:
    package com.RR4;
    import java.util.Observable;
    import java.io.*;
    * LocalFile: class reading local file when no live content is sent to the relay
    public class LocalFile extends Observable implements Runnable {
         // filenames is an array containing a list of files to be read when no live content is sent
         private String[] filenames = {
              "file1",
              "file2"
         private InputStream stream;
         boolean streamOpened;
         private StreamRelay parent;
         int fileIndex;
         // Constructor: initialises LocalFile
         //  sets fileIndex to 0, and sets main StreamRelay as Observer
         public LocalFile(StreamRelay parent) {
              this.parent = parent;
              fileIndex = 0;
              this.addObserver(parent);
              initStream();
          * initStream: initialises stream to read the next file in 'filenames' array
         public void initStream() {
              try {
                   stream = new BufferedInputStream(new FileInputStream(filenames[fileIndex]), StreamRelay.BUFFER_SIZE);
                   streamOpened = true;
                   fileIndex++;
                   if (fileIndex==filenames.length)
                        fileIndex = 0;
              } catch (Exception exp) {
                   exp.printStackTrace();
                   streamOpened = false;
          * run: main loop of the class.
          *     the file is actually read: a buffer of BUFFER_SIZE is filled and sent to
          *     the observer (StreamRelay)
         public void run() {
              byte[] buffer = new byte[StreamRelay.BUFFER_SIZE];
              byte[] bufferToSend;
              boolean quit = false;
              int actualBufferSize = 0;
              while (!quit) {
                   try {
                        this.setChanged();
                        // Bytes are read until the buffer is actually filled with BUFFER_SIZE bytes
                        // Only then is it sent to the observer...
                        while (streamOpened && ((actualBufferSize = stream.read(buffer, 0, StreamRelay.BUFFER_SIZE)) > 0)) {
                             if (parent.clients.size()>0 && (!parent.streamFromSocket)) {
                                  if (actualBufferSize<StreamRelay.BUFFER_SIZE) {
                                       bufferToSend = new byte[actualBufferSize];
                                       System.arraycopy(buffer, 0, bufferToSend, 0, actualBufferSize);
                                       this.notifyObservers(bufferToSend);
                                  } else
                                       this.notifyObservers(buffer);
                                  this.setChanged();
                             } else {
                                  try { Thread.sleep(100); } catch (Exception exp) {}
                   } catch (Exception exp) {
                        exp.printStackTrace();
                   try { stream.close(); } catch (Exception exp) {}
                   initStream();
    StreamServer.java:
    package com.RR4;
    import java.net.ServerSocket;
    public class StreamServer extends Thread {
         private ServerSocket serverSocket;
         private boolean socketOpened;
         private StreamRelay parent;
         * StreamServer: server listening for new StreamClient
         public StreamServer(StreamRelay parent, int relayPort) {
              this.parent = parent;
              try {
                   serverSocket = new ServerSocket(relayPort);
                   socketOpened = true;
              } catch (Exception exp) {
                   exp.printStackTrace();
                   socketOpened = false;
         public void run() {
              try {
                   while (socketOpened) {
                        parent.addClient(serverSocket.accept());
              } catch (Exception exp) {
                   exp.printStackTrace();
    StreamClient.java:
    package com.RR4;
    import java.net.Socket;
    import java.util.Observer;
    import java.util.Observable;
    import java.io.*;
    * StreamClient: class representing spectators connected to view the video content
    *     whether it is live content, or local files
    public class StreamClient implements Observer {
         private Socket socket;
         private OutputStream outStream;
         private boolean connected = true;
         private StreamRelay parent;
         public StreamClient(StreamRelay parent, Socket socket) {
              this.parent = parent;
              this.socket = socket;
              try {
                   // initialises OutputStream from socket
                   outStream = socket.getOutputStream();
              } catch (Exception exp) {
                   try { outStream.close(); } catch (Exception e) {}
                   try { socket.close(); } catch (Exception e) {}
                   exp.printStackTrace();
                   connected = false;
              if (connected) {
                   // if initializing of OutputStream didn't fail
                   // add this class to StreamBroadcast 'clients' vector
                   // and add this class to StreamRelay observers
                   parent.clients.add(this);
                   parent.addObserver(this);
          * update: actually send read bytes to the client
         public void update(Observable observable, Object obj) {
             try {
                   outStream.write( (byte[]) obj);
                   outStream.flush();
              } catch (Exception exp) {
                   // if read bytes couldn't be sent
                   // remove this client from clients list and observers of StreamRelay
                   // and try to close OutputStream and Socket
                   connected = false;
                   try { parent.deleteObserver(this); } catch (Exception e) {}
                   try { parent.clients.remove(this); } catch (Exception e) {}
                   try { outStream.close(); } catch (Exception e) {}
                   try { socket.close(); } catch (Exception e) {}
    LiveServer.java:
    package com.RR4;
    import java.net.ServerSocket;
    * LiveServer:
    *     SocketServer listening to new 'Live streams'
    public class LiveServer extends Thread {
         private ServerSocket liveSocket;
         private boolean liveServerOpened;
         private StreamRelay parent;
         public LiveServer(StreamRelay parent, int livePort) {
              this.parent = parent;
              try {
                   liveSocket = new ServerSocket(livePort);
                   liveServerOpened = true;
              } catch (Exception exp) {
                   exp.printStackTrace();
                   liveServerOpened = false;
         public void run() {
              LiveStream liveStream;
              try {
                   while (liveServerOpened) {
                        liveStream = new LiveStream(parent, liveSocket.accept());
                        new Thread(liveStream).start();
              } catch (Exception exp) {
                   exp.printStackTrace();
    LiveStream.java:
    package com.RR4;
    import java.util.Observable;
    import java.io.*;
    import java.net.Socket;
    *     LiveStream:
    *          Socket receiving live content from another distant computer
    *          to display it instead of the local files.
    public class LiveStream extends Observable implements Runnable {
         private InputStream stream;
         boolean streamOpened;
         private StreamRelay parent;
         public LiveStream(StreamRelay parent, Socket socket) {
              this.parent = parent;
              this.addObserver(parent);
              try {
                   stream = new BufferedInputStream(socket.getInputStream(), StreamRelay.BUFFER_SIZE);
                   streamOpened = true;
              } catch (Exception exp) {
                   exp.printStackTrace();
                   streamOpened = false;
         public void run() {
              byte[] buffer = new byte[StreamRelay.BUFFER_SIZE];
              byte[] bufferToSend;
              int actualBufferSize = 0;
              try {
                   this.setChanged();
                   // Bytes are read until the buffer is actually filled with BUFFER_SIZE bytes
                   // Only then is it sent to the observer...
                   while (streamOpened && ((actualBufferSize = stream.read(buffer, 0, StreamRelay.BUFFER_SIZE)) > 0)) {
                        if (!parent.streamFromSocket)
                             parent.streamFromSocket = true;
                        if (parent.clients.size() > 0) {
                             if (actualBufferSize<StreamRelay.BUFFER_SIZE) {
                                  bufferToSend = new byte[actualBufferSize];
                                  System.arraycopy(buffer, 0, bufferToSend, 0, actualBufferSize);
                                  this.notifyObservers(bufferToSend);
                             } else
                                  this.notifyObservers(buffer);
                             this.setChanged();
                        } else
                             try { Thread.sleep(100); } catch (Exception exp) {}
              } catch (Exception exp) {
                   exp.printStackTrace();
              } finally {
                   try { stream.close(); } catch (Exception exp) {}
                   this.deleteObserver(parent);
                   parent.streamFromSocket = false;
    }For your information, I uses NSV/VP6 vbr as video codec (but this should have no incidence on it, since the app only takes the video stream from a socket and broadcasts it to other sockets, without analysing it or modifying it). And the java app is hosted on a Celeron 2.6 GHz, 128MB RAM.
    I really hope you'll be able to help me with this project, as it is really important to me...
    I've been trying several Stream types available with the JDK but I hadn't any success... I've also been playing with the BUFFER_SIZE parameter, unsuccessfully too...
    Anyway, thanks in advance for reading me so far... and I hope, for helping me... I know the java community is strong, and I hope I won't have to make it with C or C++ :(

    Hi again :)
    I've been focusing on the local part of the stream (no live video, just playing local files and sending them to clients) using NIO.
    NIOStreamRelay.java:
    package com.RR4;
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.nio.channels.spi.*;
    import java.net.*;
    import java.util.*;
    public class NIOStreamRelay {
         static int BUFFER_SIZE = 1024;
         LocalFile localFile;
         Vector clients;
         public NIOStreamRelay() throws IOException {
              localFile = new LocalFile(this);
              new Thread(localFile).start();
              clients = new Vector();
              acceptConnections();
         public void acceptConnections() throws IOException {          
              // Selector for incoming requests
              Selector acceptSelector = SelectorProvider.provider().openSelector();
              // Create a new server socket and set to non blocking mode
              ServerSocketChannel ssc = ServerSocketChannel.open();
              ssc.configureBlocking(false);
              // Bind the server socket to the local host and port
              InetAddress lh = InetAddress.getLocalHost();
              InetSocketAddress isa = new InetSocketAddress(lh, 8080);
              ssc.socket().bind(isa);
              // Register accepts on the server socket with the selector. This
              // step tells the selector that the socket wants to be put on the
              // ready list when accept operations occur, so allowing multiplexed
              // non-blocking I/O to take place.
              SelectionKey acceptKey = ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);
              int keysAdded = 0;
              // Here's where everything happens. The select method will
              // return when any operations registered above have occurred, the
              // thread has been interrupted, etc.
              while ((keysAdded = acceptSelector.select()) > 0) {
                  // Someone is ready for I/O, get the ready keys
                  Set readyKeys = acceptSelector.selectedKeys();
                  Iterator i = readyKeys.iterator();
                  // Walk through the ready keys collection and process date requests.
                  while (i.hasNext()) {
                        SelectionKey sk = (SelectionKey)i.next();
                        i.remove();
                        // The key indexes into the selector so you
                        // can retrieve the socket that's ready for I/O
                        ServerSocketChannel nextReady = (ServerSocketChannel)sk.channel();
                        // Accept the date request and send back the date string
                        Socket s = nextReady.accept().socket();
                        OutputStream socketStream = s.getOutputStream();
                        StreamClient newClient = new StreamClient(socketStream, this);
                        localFile.addObserver(newClient);
                        clients.add(newClient);
         public static void main(String[] args) {
              try {
                   NIOStreamRelay streamRelay = new NIOStreamRelay();
              } catch (Exception e) {
                   e.printStackTrace();
    LocalFile.java:
    package com.RR4;
    import java.util.Observable;
    import java.io.*;
    * LocalFile: class reading local file when no live content is sent to the relay
    public class LocalFile extends Observable implements Runnable {
         // filenames is an array containing a list of files to be read when no live content is sent
         private String[] filenames = {
              "test.nsv",
              "test2.nsv"
         private InputStream stream;
         boolean streamOpened;
         int fileIndex;
         NIOStreamRelay parent;
         // Constructor: initialises LocalFile
         //  sets fileIndex to 0, and sets main StreamRelay as Observer
         public LocalFile(NIOStreamRelay parent) {
              this.parent = parent;
              fileIndex = 0;
              initStream();
          * initStream: initialises stream to read the next file in 'filenames' array
         public void initStream() {
              try {
                   stream = new BufferedInputStream(new FileInputStream(filenames[fileIndex]), NIOStreamRelay.BUFFER_SIZE);
                   streamOpened = true;
                   fileIndex++;
                   if (fileIndex==filenames.length)
                        fileIndex = 0;
              } catch (Exception exp) {
                   exp.printStackTrace();
                   streamOpened = false;
          * run: main loop of the class.
          *     the file is actually read: a buffer of BUFFER_SIZE is filled and sent to
          *     the observer (StreamRelay)
         public void run() {
              byte[] buffer = new byte[NIOStreamRelay.BUFFER_SIZE];
              byte[] bufferToSend;
              boolean quit = false;
              int actualBufferSize = 0;
              while (!quit) {
                   try {
                        this.setChanged();
                        // Bytes are read until the buffer is actually filled with BUFFER_SIZE bytes
                        // Only then is it sent to the observer...
                        while (streamOpened && ((actualBufferSize = stream.read(buffer, 0, NIOStreamRelay.BUFFER_SIZE)) > 0)) {
                             if (parent.clients.size() > 0) {
                                  if (actualBufferSize<NIOStreamRelay.BUFFER_SIZE) {
                                       bufferToSend = new byte[actualBufferSize];
                                       System.arraycopy(buffer, 0, bufferToSend, 0, actualBufferSize);
                                       this.notifyObservers(bufferToSend);
                                  } else
                                       this.notifyObservers(buffer);
                                  this.setChanged();
                             } else {
                                  try { Thread.sleep(100); } catch (Exception exp) {}
                   } catch (Exception exp) {
                        exp.printStackTrace();
                   try { stream.close(); } catch (Exception exp) {}
                   initStream();
    StreamClient.java:
    package com.RR4;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class StreamClient implements Observer {
         OutputStream out;
         NIOStreamRelay parent;
         public StreamClient(OutputStream out, NIOStreamRelay parent) {
              this.out = out;
              this.parent = parent;
         public void update(Observable observable, Object obj) {
             try {
                   out.write( (byte[]) obj);
                   out.flush();
              } catch (Exception exp) {
                   // if read bytes couldn't be sent
                   // remove this client from clients list and observers of StreamRelay
                   // and try to close OutputStream and Socket
                   try { parent.localFile.deleteObserver(this); } catch (Exception e) {}
                   try { parent.clients.remove(this); } catch (Exception e) {}
                   try { out.close(); } catch (Exception e) {}
    }Does it look better to you?
    I know I'm still using single threading, but as the IO should be non-blocking, I guess it should be better.
    Furthermore, I tried it locally, and was able to launch 30+ clients without buffering problems (huh, ok, my cpu here is only a 1.6GHz, so the display was a bit lagguy, but it didn't seem to buffer at all)

  • How to make a peer to peer connection in a network using sockets

    My Project is about a multi agent meeting scheduling system.. I've kept the DB in the server and I only use the server to retrieve data from the database. I have used sockets to communicate with the server.
    Each peer in the network is an agent for a perticular user and these agents will be communicating with each other for negotiation purposes..
    The problem I have is that, I couldnt communicate wit other peers using sockets.. I couldnt find any sample java code of sockets to overcum this problem.f sumone has a sample code plz send me.
    And if there is a more efficient and easy way I can connect these peers except sockets, plz tell me and if u have a sample java code plz be kind enough to send.
    This is my final year project in the University
    Thank you
    Sajini De Silva ([email protected])

    Hi Sajinidesilva,
    I think you'll find more support in the [JXTA Community|https://jxta.dev.java.net/] for your project. Also, there's an interesting article to start with : [Introduction to the Peer-to-Peer Sockets Project|http://www.onjava.com/pub/a/onjava/2003/12/03/p2psockets.html].

  • Two applications wants to read on the same port using Socket

    I have an application running on one machine using TCP/IP socket. The data transfer with the other application on other machine is in ASCII.
    Now I want a new application that can have a copy of data received and sent on the given port, where the previous application is running.
    Is it possible in Java using socket and TCP/IP to have two application reading data from the same port and both can read all the data.

    Even when you don't state the type of app which need to read the data stream (is it a server or a client app???), it's impossible to share a single TCP/IP socket among multiple apps.
    Perhaps the best thing to do is to develop something like a proxy server who listens on the nominated port and provides to contact (if your apps are server ones) or to be contacted (if your apps are client ones) by the desired apps.
    This way, the only job for the proxy is to duplicate the contents of the data stream and make them available to all the apps engaged.
    Hope this helps.

  • Using StreamConnection with MMAPI emulator

    Hi,
    I am using StreamConnection class to establish a socket connection with my server. If I run the application on PalmOS PDA it works fine. But when I run it in the mobile media emulator it does not connect to the server.
    Does anyone know why?
    These are the things I tried:
    1. I tried using HttpConnection instead of StreamConnection and the application is able to connect to the server on the mmapi emulator but unable to retrieve data (as I wrote teh program keeping StreamConnection in mind....this probably can be fixed, but I wanted to make it work with the StreamConnection class using sockets so that I dont have to change my programs.)
    2. I checked to see if the StreamConnection class files are present in the api zip file and I found all io classes in this zip file emptymmapi.zip
    I really dont know why it wouldn't connect using StreamConnection....
    Any answers would be really appreciated....

    The StreamConnection undoubtedly exists but sockets might not be supported.
    MIDP doesn't require sockets to be implemented so maybe opening a socket connection (socket://url:port) is impossible. Aren't you getting some "Connection scheme not supported" type exception when trying to create the StreamConnection?

Maybe you are looking for