Socket OutputStream

Hi,
I've been working on something with a friend of mine, which includes server-client communications, and I've encountered something that I can't understand. What's happening, is, well, I'll just show you an SSCCE and then make it simple under that.
SSCEE:
public class Main {
     private static Connection connection;
     private static Connection connectionTwo = new Connection("0.0.0.0", 5555);
     public static void main(String[] args) {
          connection = new Connection("0.0.0.0", 5555);
          System.out.println("connection: " + connection.getOutStream());
          System.out.println("connectionTwo: " + connectionTwo.getOutStream());
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Connection extends Thread {
     private Socket socket;
     private OutputStream outStream;
     private InputStream inStream;
     public Connection(String ip, int port) {
          try {
               socket = new Socket(ip, port);
               outStream = socket.getOutputStream();
               inStream = socket.getInputStream();
          } catch (UnknownHostException e) {
               e.printStackTrace();
          } catch (IOException e) {
               e.printStackTrace();
     public Socket getSocket() {
          return socket;
     public InputStream getInStream() {
          return inStream;
     public OutputStream getOutStream() {
          return outStream;
* Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*   - Neither the name of Oracle or the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(5555);
            System.out.println("Server listening on *:5555");
        } catch (IOException e) {
            System.err.println("Could not listen on port: 5555.");
            System.exit(1);
        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException e) {
            System.err.println("Accept failed.");
            System.exit(1);
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        out.close();
        in.close();
        clientSocket.close();
        serverSocket.close();
}What happens, is, when setting connection via the main method, and then grabbing it below it, i receive 'null' as the variables value, yet if I set connectionTwo via the method declaration it will grab it fine and dandy.
I'm not using that same exact example, but it's relatively similar, and I'm using xSocket for networking, and as far as I know, SSCCE's don't call of included libraries. In my example if I set the connection variable via the declaration, all is well, yet if I set it inside of a method and then call it, it doesn't go too well.
I hope I explained this well enough, thanks for any help in advance.

The Connection refused exception that your example code throws means that there is not a server listening on the designated host/port combination.
The problem is that your server code sample does not contain a loop, so it will only accept the first client connection it sees. In this case, the static object connectionTwo is instantiated when the class is loaded - before the main method executes and attempts to create the object connection.
Typically I would expect to see some type of loop around serverSocket.accept( ) and then passing the client connection off to a separate worker thread to actually process the request.

Similar Messages

  • String is broken while writing to Socket Outputstream

    Hi all,
    I am constructing an XML response in the following way
    public String constructXML() {
    StringBuffer sb = new StringBuffer();
    sb.append("<emp>");
    sb.append("<emp id="\"");
    sb.append(empInfo.getEmpID());
    sb.append("\"");
    sb.append("<emp name="\"");
    sb.append(empInfo.getEmpName());
    sb.append("\"");
    sb.append("<emp age="\"");
    sb.append(empInfo.getEmpAge());
    sb.append("\"");
    sb.append("</emp>");
    return sb.toString();
    }In another method, I am opening a socket and writing to the outputstream
    public void writeToSim(String response) {
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    out.println(response);
    out.flush();
    out.close();
    }My constructed xml response is very huge and I am getting the response like this
    <emp>
    <emp id="111"/>
    <emp name="sss"/>
    <emp age = "33"/>
    </emp>
    <emp>
    <emp i d="111"/> // note the space between i and d.
    <emp name="sss"/>
    <emp age = "33"/>
    </emp>
    <emp>
    <emp id="111"/>
    <emp name="sss"/>
    <emp a ge = "33"/> // note the whitespace between a and ge
    </emp>
    I dont know how these tags are broken. Could any one give me a pointer?

    That source code can't possibly produce that output. All the inner <emp> elements are terminated by /> in the output you've shown, but there's nothing in the code you've shown that creates the terminating />.
    So check your source code. None of the methods you are calling will insert a space. Clearly it is your actual source code that's doing that, or something you haven't shown here.
    BTW this is very strange XML. You normally wouldn't have <emp> elements inside another <emp> element anyway. Are you sure this is what's required? I suspect it should really look like this:
    <emp id="111" age="3" ... />
    or
    <emp>
    <id>111</id>
    <age>33</age>
    </emp>
    or possibly
    <emp>
    <id value="111"/>
    <age value="33"/>
    </emp>

  • Socket writing error (URGENT!)

    Hi,
    I'm working on NT4.0 with jdK1.2.
    I'm writing an array of bytes in a Socket OutputStream. The size of the array is about 7k.
    The problem is that i often get a socket writing error(code error = 10053).
    Could anybody help me about this?
    Thanks

    Socket error 10053 occurs when the software causes the connection to be dropped.
    Couple of reasons why this would happen:
    1. There is no space on the socket's queue and the socket cannot receive further connections.
    2. The receiver never acknowledges data sent on a datastream socket.
    To work around this issue, you could try sending the data after setting "TCP_NODELAY" to "false". This needs to be done before you get the input/output streams, and enables Nagles algorithm. A side efect is that the sending becomes slower.
    You could also try acknowledging smaller packets of data.

  • 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)

  • Image transfer through *socket*

    hi.
    can anyone plz show how to send a PNG image file through a raw socket outputStream (from a j2se server to a midlet) ???
    thanks

    You will have to take care of indentation.
    midlet code:
    //SOCKET ---------------------------------------------------------------
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import java.io.*;
    import javax.microedition.io.*;
    public class Main extends MIDlet implements Runnable
         private Thread t;
         private Display display;
         private Form form;
         private Command exitCommand, getCommand;
         private String connectionDetails "socket://10.10.100.109:1500";
         private InputConnection ic;
         private DataInputStream dis;
         public Main()
              //create the backCommand, okCommand and the exitCommand
              exitCommand = new Command("Exit", Command.EXIT, 1);
              //creating the form
              form = new Form("CONNECTING......");
              form.addCommand(exitCommand);
              System.out.println("exit command and get command were appended to the form");
              //instantiating the listener
              CommandListener listener = new CommandListener()
                   public void commandAction(Command c,Displayable d)
                        if(c==exitCommand)
                             System.out.println("exitCommand as pressed");
                             exit();
                   public void exit()
                        destroyApp(true);
                        notifyDestroyed();
              //setting the listeners
              form.setCommandListener(listener);
              //getting the display object
              display = Display.getDisplay(this);
         public void startApp()
              display.setCurrent(form);
              System.out.println("form was set as the currentscreen");
              t = new Thread(this);
    t.start();
         public void pauseApp()
         public void destroyApp(boolean cond)
              display = null;
              form = null;
              exitCommand = null;
    public void run()
         while(true)
                                  try
                                       //establishing a connection with the remote server
                                       System.out.println("about to get a stream connection");
                                       ic = (InputConnection)Connector.open(connectionDetails,Connector.READ);
                                       System.out.println("input connection was created");
                                       //input stream is created on top
                                       //of the stream connection object
                                       dis = ic.openDataInputStream();
                                       System.out.println("input stream was created");
                                       //receiving data
                                       byte []ib = new byte[10000];
                                       int length = dis.read(ib);
         System.out.println("BYTES RECEIVED "+length);
         /*for(int k= 0;k<length;k++)
              System.out.println("byte["+k+"]="+ib[k]);
                                       //displaying the received data
                                       if(form.size()!=0)
                                            form.delete(0);
                                       form.append(Image.createImage(ib,0,length));
                                       //form.append(new StringItem("DOLLAR NIS exchange rate is ", sb.toString()));
                                  catch(Exception e)
                                       if(form.size()!=0)
                                            form.delete(0);
                                       form.append(new StringItem("problem:",e.getMessage()));
                                  finally
                                       //releasing resources that were allocated
                                       try
                                            if(dis!=null)
                                                 dis.close();
                                       catch(IOException e)
                                            e.printStackTrace();
                                       try
                                            if(ic!=null)
                                                 ic.close();
                                       catch(IOException e)
                                            e.printStackTrace();
                   try{Thread.sleep(1000);}catch(Exception e){e.printStackTrace();}
    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    Server code:
    // tcpServer.java by fpont 3/2000
    // usage : java tcpServer <port number>.
    // default port is 1500.
    // connection to be closed by client.
    // this server handles only 1 connection.
    package sock;
    import java.net.*;
    import java.io.*;
    public class ImageServer {
         public static int counter = 0;
         public static final int counter_end = 4;
    public static void main(String args[]) {
         int port;
         ServerSocket server_socket;
         BufferedReader input;
         OutputStream output;
         try {
         port = Integer.parseInt(args[0]);
         catch (Exception e) {
         System.out.println("port = 1500 (default)");
         port = 1500;
         try {
         server_socket = new ServerSocket(port);
         System.out.println("Server waiting for client on port " +
                   server_socket.getLocalPort());
         // server infinite loop
         while(true) {
              Socket socket = server_socket.accept();
              System.out.println("New connection accepted " +
                        socket.getInetAddress() +
                        ":" + socket.getPort());
              //input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    output = socket.getOutputStream();
              // print received data
              try
    byte []ib=getCurrentFileBytes();
    System.out.println("BYTES TO SEND "+ ib.length);
    output.write(ib);
    output.flush();
    output.close();
              catch (IOException e) {
              System.out.println(e);
              // connection closed by client
              try {
              socket.close();
              System.out.println("Connection closed by client");
              catch (IOException e) {
              System.out.println(e);
         catch (IOException e) {
         System.out.println(e);
    private static byte[] getCurrentFileBytes() throws IOException
              byte []ret = getFileBytes("c:/temp/ts"+counter+".png");
              if(counter == counter_end)counter = 0;
              else counter++;
              return ret;
    private static byte[] getFileBytes(String FileName) throws IOException
              byte[] lReturn = null;
              try
                   FileInputStream fis = new FileInputStream(FileName);
                   lReturn = getBytes(fis);
                   fis.close();
              catch(Exception e)
                   e.printStackTrace();
                   throw new IOException();
              return lReturn;
    private static byte[] getBytes(InputStream inputStream)
    byte finalBuffer[] = null;
    int receiveBufferSize = 1000;
    byte receiveBuffer[] = new byte[receiveBufferSize];
    int offset = 0;
    int length = 0;
    int bytesRead = 0;
    try
    while(inputStream.available() > 0)
    bytesRead = inputStream.read(receiveBuffer,offset,
    receiveBufferSize);
    byte temp[] = new byte[length + bytesRead];
    if(length>0)System.arraycopy(finalBuffer,0,temp,0,length);
    System.arraycopy(receiveBuffer,0,temp,length,bytesRead);
    finalBuffer = temp;
    length = length + bytesRead;
    catch(IOException ioe)
    ioe.printStackTrace();
    finalBuffer = new byte[0];
    return finalBuffer;

  • Howto connect with http to a socket - header problem?

    Hi
    i am writing a midlet that connects via http to a server with a java socket.
    i can receive the data, but when i try to return data to the sockets outputstream,
    the midlet doesnt receive it and waits endlessly.
    Do i have to send a http header in the return connection?
    Does anybody have another idea?
    if not, how do i send the header and how should it look like?
    Thanks for your help.
    Mathis

    if you use a socket connection you need to talk the language the server understands, means, you need to send the commands that are specified in the rfc for the protocol you use. means, talking to a webserver is different that talking to pop3 server or to a ftp server.....
    and, just for your information: sockets are not requiered in the j2me specification, means that not all vendors have implemented socket protocol into their devices. only required is http.

  • Synchron communication via Socket

    Hi everyone,
    Is there a way to make TCP Sockets communicate in a synchron manner?
    I mean, I send a message over a socket and be blocked until I receive
    the answer.
    (PS: I don't want to use any other API (like RMI, or JMS or etc etc).
    I ask, whether the Socket implementation in java.net package can do
    this implicitly.)
    Thank you very much

    No no, this is not a ServerSocket anyway. Assume there is just
    one Socket that is already connected.
    I send a message, i.e. I call for example
    outputstream.println("....");
    where 'outputstream' is the Stream that I obtained using my socket.
    Normally my code continues to run after that line. If I expect
    an answer, I receive it via an "response from the other side- event".
    But for example consider RMI. If I call a method of a remote object,
    Object o = remoteobj.aMethod();
    then my thread is blocked until I receive a response from the
    remoteobj. I do not have to listen to an additional event, everything
    is done synchronously.
    I want to do the same thing as RMI with my socket (outputstream).
    I want my code to be blocked until I receive an answer from the
    other side.
    That was my question.
    Best Regards
    I mean, I send a message over a socket and beblocked
    until I receive
    the answer.Do you mean by being blocked you do not have a socket
    listening anymore to make additional connections?

  • Transfering files via sockets

    Hi
    I am writing a client server app, and am communicating between the clients and server using the Socket and Serversocket class's. Transfering strings is very easy, but i also want to transfer files. I usually use Fileinputstream/fileoutputstream in normal circumstances, but i dont think this will work with sockets.
    Any suggestions on how i can transfer files through a sockets would be most welcome.
    Cheers
    Steve

    Just create the InputStream to your file, read in some bytes, write the bytes to the sockets OutputStream, voila!
    Rob.

  • Some files I can't read and write to my socket!?

    I have the following code that writes files to my socket:
    OutputStream out = new BufferedOutputStream(socket.getOutputStream());
    File f = new File(SOME_PATH);
    InputStream fin = new FileInputStream(f);
    int n;
    while((n = fin.read()) > 0) {
      out.write(n);
    out.flush();
    fin.close();And the following reads this file from the socket, and writes it to another file on the server:
    InputStream in = new BufferedInputStream(socket.getInputStream());
    File f = new File(SOME_PATH);
    OutputStream vos = new FileOutputStream(f);
    int n;
    for(int i=0;i<fileSize;i++) {
      n = in.read();
      vos.write(n);
    vos.close();
    vos = null;"fileSize" is always the size of the file, I'm pretty sure here.
    I can transfer both binary and text files, but not all text files. Why is that? How do I fix it?

    Another way is to have an object that represents the file...and then it can contain the filename and other stuff...
    public class MyFile
       private String filename = "";
       private byte[] filecontents = null;
    }If you then use an ObjectOutput/InputStream then you can read the file in wholesale...
    However if you are having "other" commands that you read from the stream then it wouldn't solve that problem!
    Another way is to use the ISDN method, more complex but effective, that is to have a control channel and a data channel...i.e. one stream for sending commands, another for sending data in response to commands...one issue there though is that of synchronization...
    Another potential method is to use XML to provide a "data envelope" that encapsulates the file...
    i.e.
    <file filename="[name]">
    <![CDATA[
       <!-- File contents go here, could be binary/plain text -->
    ]]>
    </file>Of course using XML in this way has it's own problems...
    Overall if you already have a working system in place then I'd stick with that, but those are some ideas!!!

  • DataOutputStream from Socket

    pls anytime i load large jpeg(about 10kb) images from database(Mysql) and send primitive types before it and then the picture bytes using DataOutputStream created from a socket outputstream, there occur sporadic errors sometimes but not all the time. When i reduced the picture size to about 3kb, it works fine.
    Anybody with solution please!

    You need to check that you are:
    - Using DataOutput/InputStream the whole time, not just for the image
    - You are reading the whole imagine, you cannot use available or assume that the imagine will come in a single package.
    The simplest way to resolve this is to send the size of the image, before the image itself.
    e.g.// to write
    byte[] imageBytes;
    dataOutput.writeInt(imageBytes.length);
    dataOutput.write(imageByte);
    // to read.
    int length = dataInput.readInt();
    byte[] imageByte = new byte[length];
    dataInput.readFully(imageByte);

  • AccessControlException when establishing socket connecion within servlet

    Hello good people!
    I need to use a socket connection within the function doGet() of HttpServlet.
    The code is as following:
    public void doGet (HttpServletRequest request,
              HttpServletResponse response) throws ServletException, IOException
         Socket socket;
         OutputStream outStream;
         InputStream inStream;
         String transID;
         PrintWriter out = null;
         transID = request.getParameter("transID");
         try
              out = response.getWriter();
    response.setContentType("text");
              //creation and connection of socket.
              socket = new Socket("147.161.2.170", 7665);
    outStream = socket.getOutputStream();
              inStream = socket.getInputStream();
              outStream.write(transID );
              byte[] locRes = new byte[ANSWER_SIZE];
              int readSize = inStream.read(locRes);
              locStr = new String(locRes, 0, readSize);
              out.println("hello");
         catch(Exception e)
              out.println(e.getMessage() + " " + e.toString());     
    Lhe line "socket = new Socket("147.161.2.170", 7665);" causes an Exception which is caught in the catch clause, and as result I get the following:
    access denied (java.net.SocketPermission 147.161.2.170:7665 connect,resolve) java.security.AccessControlException: access denied (java.net.SocketPermission 147.161.2.170:7665 connect,resolve)
    What's its problem??
    Is there any problem in establishment of socket connection within a HttpServlet?
    Please help, all of you!
    Thanks beforehand

    someone hears me???
    help!!!

  • Socket doen't detect broken network.

    the following server program just keeps on running when I unplug the clients network kabel. (client is just a telnet)
    If I send to the socket outputstream he doesn't detect the broken link.
    jdk 1.4.1
    linux.
    java.net.ServerSocket serverSocket= new java.net.ServerSocket(3201);
    java.net.Socket socket = serverSocket.accept();
    java.io.DataOutputStream lS = new java.io.DataOutputStream(socket.getOutputStream());
    while(true)
    lS.writeUTF("test");
    lS.flush();
    System.out.println("testing");
    Thread.sleep(1000);
    }

    yep, pain in the neck isnt it...
    reason is that TCP/IP is not a permanent type of connection, rather a serise of packets between 2 sockets, if you terminate the connection "properly" then an EOF is sent by the closing Socket, if however there is a network failure then it can never be recieved The expected work around is with Socket.setSO_TIMEOUT, but this has been reported to be unreliable and the standard method for detecting a broken connection is to write your own timeout and either close the socket, or attempt to write something to it (which will throw an IOException) if it has failed

  • Compressing and uncompresing chunks of audio data

    Hello,
    I am doing a project in Java, it has a server and a client, the aim of server is to read an audio file (a .WAV file, actually ) chunk by chunk and compress is it to certain quality (using both lossy and lossless techniques) as specified by the client and transmit it, the client will decompress it and play it out. I am using two ports for it, one for control signals, another for the actual audio data transmission. So far I, my application initiates the GUI, looks up servers, connects to it after finding one using the two ports, gets audio files' list and plays the clip.
    playing is done by reading the wav file using FileIputStream, 128*1024 bytes at a time, writing it to socket outputstream. On client side this stream is used to create the audio format object and play the clip. Obviously, this is not the way it is to be done, correct? what's the best way of encoding that 128*1024 byte chunk so that it can be re created on client?
    The code that I've got together looks something like this:
    STREAMER:
    dataOut = dataSocket.getOutoutStream();
    fis = new FileInputStream( new File(fileName));
    byte[] b = new byte[1024];
    try{
    while (fis.available()!=0) {
         fis.read(b);
         dataOut.write(b);
    catch( .. ) {  }CLIENT:
    dataIn = dataSocket.getInputStream();
    try {
        while (dataIn.available()!=0) {
         play(din);
    catch ( ..) { }
    void play(InputStream is){
    ..  // here AudioInputStream object is created using getAudioInputStream(is)
    ..  //an AudioFoamat object is created using audioInputStream.getFormat();
    //then a default audioFormat is created , changing the encoding to PCM_SIGNED and bit-dept to 16
    //then using this default format, we play the audio:
    //we construct an AudioInputStream using this default format. then play using this audioInputStream.
        DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
        SourceDataLine line = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
        line.open(audioFormat);
        line.start();
    byte[] abData = new byte[128*1024];
      int nBytesRead = 0
      while (nBytesRead != -1) {
         try {
          nBytesRead = audioInputStream.read(abData, 0, abData.length);
          } catch( .. ) {  }
         if (nBytesRead >= 0) {
           line.write(abData, 0, nBytesRead);
      }

    thanks captfoss, yes the thing i am developing looks like RTP, i'll go through them.
    now i am looking for some java codes that will convert raw audio bytes to mp3 encoded byte stream, the only things around are things from LAME project, being written entirely in C, this is not a very attractive alternative.. i would rather have clean and simple Java libraries that will encode chunks of raw audio to compressed byte streams, please help me find some such libraries,
    thanks in advance,
    diemond

  • A2DP API for bluetooth?

    Hi,
    I want to send a sound to a a BT module. This module is like a headset.
    I searched everywhere for a BT example for WP8 but I can't find any help.
    I have this code:
    StreamSocket socket = new StreamSocket();
    await socket.ConnectAsync(peer.HostName, "1");
    Why "1"? In the sample, RFCOMM is selected. If I want A2DP, what should I write?
    Another question is: is there an API for A2DP? The protocol is really hard to understand. And I don't know where to begin if I have to write all without any library... All with socket.OutputStream()?
    Hope someone can help me with this problem.
    Thank you!
    Adriano

    Thank you very much Mark,
    I was afraid, that it was not possible.
    WP8 has the A2DP and  AVRCP protocol, but developers have to write again the entire protocol that is already present in the system to communicate with BT speakers?
    I want to send 2 audio streams to 2 BT-speakers at the same time. Do you think, is it possible with Windows Phone 8?
    From your links, I saw that there is a way to send data to the device without RFCOMM.
    Old code:
    StreamSocket socket = new StreamSocket();
    await socket.ConnectAsync(peer.HostName, "1");
    New code:
    StreamSocket socket = new StreamSocket();
    await socket.ConnectAsync(peer.HostName, "{0000110D-0000-1000-8000-00805F9B34FB}");
    DataWriter dataWriter = new DataWriter(socket.OutputStream);
    DataReader dataReader = new DataReader(socket.InputStream);
    AdvancedAudioDistributionService: GUID = {0000110D-0000-1000-8000-00805F9B34FB}
    AudioSourceService: GUID = {0000110A-0000-1000-8000-00805F9B34FB}
    HeadsetService: GUID = {00001108-0000-1000-8000-00805F9B34FB}
    I will try with this.
    Thank you again for the links. Once I got it, I will insert a little example on this topic. Maybe it can help someone.
    Adriano

  • Displaying image on applet

    i have a server and a client program... i need to send an image from the server program and display it on the applet.... i think it can be done by ImageIcon(byte[] ImageData) in the applet.... i hope someone writes a code for me to make stream of byte of the image on the server side and recieve the stream on the applet side and display the image....
    Thanks in advance...
    Uzair

    public class Server {
        private static final int port = 2573;
        public static void main(String[] args) {
            FileInputStream FIS;
            try {
                FIS = new FileInputStream(args[0]);
            }catch(Exception e) {
                e.printStackTrace();
                return;
            byte[] data = new byte[FIS.available()];
            FIS.read(data);
            FIS.close();
            System.out.println("Image read. Waiting for client...");
            Socket socket;
            OutputStream stream;
            try{
                socket = (new ServerSocket(port)).accept();
                stream = socket.getOutputStream();
            }catch(Exception e){
                e.printStackTrace();
                return;
            System.out.println("Client connected. Sending image...");
            stream.write(data);
            stream.close();
            System.out.println("Done. Good Luck Client!");
    public class Client {
        private static final String host = "localhost";
        private static final int port = 2573;
        public static void main(String[] args) {
            System.out.println("Connecting to Server...");
            Socket socket;
            InputStream stream;
            byte[] buffer = new buffer[1048576], data;
            int i, read, total = 0;
            ImageIcon image;
            try{
                socket = new Socket(host, port);
                stream = socket.getInputStream();
                System.out.println("Connected. Reading data...");
                while((read = stream.read(buffer, total, buffer.length - total)) >= 0)
                    total += read;
                data = new byte[total];
                System.arraycopy(buffer, 0, data, 0, total);
                image = new ImageIcon(data);
            }catch(Exception e){
                e.printStackTrace();
                return;
            System.out.println("Image retrieved! Doing something about it now...");
            //Your code for displaying the image somewhere in the applet
    }Hope this helps~
    Alex Lam S.L.

Maybe you are looking for

  • Windows - Mac Printer Sharing???

    I have a perfectly working HP Photosmart 7150 connected to my Windows XP PC. I also have a wireless network running through my house. I have enabled Printer Sharing and other Windows XP (and Vista) Laptops can print to it wirelessly. How do I do this

  • File Processing Methodology

    Hi, I have the following requirement from the customer. They would be appending record by record every minute in the same file and XI needs to process them into ECC. Is this possible since file locking mechanisms will create problems. The customer me

  • IPhoto crashes trying to import photo's

    My iPhoto keeps crashing/freezing as I try to import photos. It begins to import 30+ photos then freezes and requires a force quit. From other threads I have looked for plug-in s which might be causing it but none of the listed one show up I have als

  • ITunes crashing after update?

    I installed today's update (had to quit iTunes during the process), completed the install to find that iTunes would open for a split second and immediately crash. Has done every time I've tried opening it since. I'm not trying anything complicated li

  • Unable to open .cfm files

    I need to be able to open .cfm files, which were no problem in Windows. However, since switching to iMac, I am not able to open the .cfm files in Pages, Word for Mac, using Adobe Reader, etc. Does anyone else have the same problem and/or know the sol