Mixing byte & character stream over socket

Hi,
I would like to transmit a file name first to my server ( string )
then I transmit the contents of an arbitrary file ( byte )
I tried to chain two different filters to the InputStream instance returned by the socket, but it does not seem to work.
What is the best way to do that ?
Do I have to read my initial file name string by a byte stream and rebuild it ?
Tks

I Use this code
InputStream bin = socket.getInputStream();
OutputStream bout = socket.getOutputStream();
PrintWriter in = new PrintWriter( bout, true);
BufferedReader out = new BufferedReader(
new InputStreamReader(bin) );
on server and on client just change the socket reference,
The programs works fine just the first and second time and after
the second time, the PrintWriter and BufferedReader works
as an InputStream and an OutputStream, Do you know how to indicate
to the Print Writer and OutputStream that are reading text ?
TNX, Alex

Similar Messages

  • HTTP 1.1: Using streams over socket; How ?

    Can anyone give me a short example as how to handle streams over a persistent socket-connection ?
    I've trouble handling this.
    I can't "reget" the stream (create a new input/output stream over an existing socket-connection).
    Is there someone who can help me ?
    I'm getting confused !!!

    Since no one helped I could only try to find out myself:
    The problem is I used some example-source that fitted well for HTTP 1.0, but led to erroneous results when applied to HTTP 1.1
    It's no problem in HTTP 1.1, but you need to read ALL input (headers and possibly content) before trying to process anything:
    From the headers you need to read until an empty line is discovered.... Don't just break on return or newline, this will leave an extra character in the input:
    Protocol requires both \r and \n. So you always break 1 char to early when scanning bytes and then concluding on a \r that the line is over.
    Then you should possibly read 'contentlength bytes' (I've not tried it out yet) in case of POST.
    Flushing is enough to write all data to output.
    Open and close can't work. "Regetting" a stream is not possible, so all input for this request must be taken from inputstream before trying to process the next request.

  • How to convert character streams to byte streams?

    Hi,
    I know InputStreamReader can convert byte streams to character streams? But how to convert the character streams back to byte streams? Is there a Java class for that?
    Thanks in advance.

    When do you have to do this? There's probably another way. If you just start out using only InputStreams you shouldn't have that problem.

  • Passing serialized object and data as byte stream over same stream

    I am writing a chat program, I am keeping online user List as Vector A would like to pass online user List to client as Vector object also the client message is sended as byte stream. Is it possible to pass object and data as byte stream over the same stream.

    I am writing a chat program, I am keeping online user
    List as Vector A would like to pass online user List
    to client as Vector object also the client message is
    sended as byte stream. Is it possible to pass object
    and data as byte stream over the same stream.Why are you sending the client message as a byte stream?
    String seems a much more logical type. I would assume that you're reading strings from one client, and printing them on the others. If you translate to bytes in the middle, you're going to have to ensure that you decode those streams correctly on the other side.
    And if I were implementing this, I probably wouldn't send the raw Vector or List ... instead, I'd create a Message object, which wraps the Vector/String, and a MessageDispatcher interface, which the client implements to handle incoming messages.

  • Binary file transfert over socket : data corupted !

    Hi everyone,
    I am trying to transfert binary files over Socket (java.net) and I get corrupted data... I know the data I write in the Socket is ok and I wonder why I don't get it right at the end.
    Does anyone know about it ?

    Ok i have re-written it without the Packet class and it know works...
    I give my code in case someone would be interested.
    ENCODER :
    public class Encoder {
         // the file to send
         private File file;
          * Constructor of the Encoder class
          * @param path the path to the file to send
         public Encoder(String path){
              this.file = new File(path);
              this.encodeFile();
          * This method contains the connection an file tranfert code
         private void encodeFile(){
              try {
                   // opening file reading stream
                   FileInputStream fis = new FileInputStream(this.file);
                   // connection...
                   Socket sock = new Socket("127.0.0.1", 5698);
                   // opening an output stream
                   BufferedOutputStream bos = new BufferedOutputStream(sock.getOutputStream(), 1024);
                   // start time
                   long start = System.currentTimeMillis();
                   // setting up the buffer
                   byte[] buffer = new byte[1024];
                   /* ---- File Transfert Loop ---- */
                   // reading for the first time
                   int read = fis.read(buffer);
                   while (read > 0){
                        bos.write(buffer);
                        bos.flush();
                        read = fis.read(buffer);
                   /* ----End Of File Transfert ---- */
                   // end time
                   long end = System.currentTimeMillis();
                   // closing streams and connection
                   fis.close();
                   bos.close();
                   sock.close();
                   // display file transfert duration
                   System.out.println("Completed in :" + (end - start) + " ms !");
              } catch (IOException e) {
                   e.printStackTrace();
    DECODER :
    public class Decoder {
         private File destFile;
         public Decoder(String path){
              try {
                   // setting up destination file
                   this.destFile = new File(path);
                   // setting up file writting stream
                   FileOutputStream fos = new FileOutputStream(this.destFile);
                   // setting up connection server
                   ServerSocket serv = new ServerSocket(5698);
                   // accepting client connection request
                   Socket sock = serv.accept();
                   // setting up reading stream for the connection
                   BufferedInputStream bis = new BufferedInputStream(sock.getInputStream());
                   // setting up byte buffer
                   byte[] buffer = new byte[1024];
                   // first reading
                   int read = bis.read(buffer);
                   while (read != -1){
                        // writting buffer content into file
                        for (int i=0; i < read; i++){
                             fos.write(buffer);
                        // reading next bytes
                        read = bis.read(buffer);
                   //closing streams
                   fos.close();
                   bis.close();
              } catch (IOException e) {
                   e.printStackTrace();

  • Serialization over sockets

    Hi All!
    So i've decided to perform serialization over sockets - so i made a server that has an ObjectOutputStream and a client that has ObjectInputStream and i wrote a Properties object.
    I managed to get passed the EOFException problem and the same object writing problem (using reset()), but i've read that this isn't efficient, and on top it all it has the problem of blocking.
    I've read some posts regarding Serialization and NIO but i couldn't get from them what i should do - so can someone plz explain to me:
    1) How can i write objects to sockets using NIO
    2) Furthermore - if this really solves the memory and efficiency problems
    3) A code sample or a ref. would really be appriciated.
    Regards,
    Snayit

    Basically I would ask myself if I really need NIO - for MOST purposes the old-blocking IO is very good and much easier to use.
    One of the biggest problems with blocking IO is, that for thousands of clients you need an own thread which causes many OSes to truggle.
    I really recommend buffering the streams! (Via BufferedInput/OutputStream) but do not forget to flush() them if you really want the data to be sent.
    If you want to use NIO you have to write the object-data into a byte-array (creating a bytearrayoutputstream -> ObjectOutputStream) and writing this byte-arrays.
    hope this helps, lg Clemens

  • Microphone Streaming over Network is Choppy

    Hello.
    Part of a program in development allows audio to be streamed over the Internet via microphone capture. The current solution seems to be working alright... however, at times the audio gets extremely choppy on the receiving side, almost to the point of being unable to hear it at all... 15 second gaps etc...
    I was wondering if you would look at this code and had any suggestions how I could improve this to make it flow better.
    Any help is appreciated. First is the server code. Second is the client (receiving code)
    public class MicrophoneManager implements Runnable {
    private static volatile ByteArrayOutputStream byteArrayOutputStream;
    private static String communicatorIP = null;
    public static volatile boolean interrupt = false;
    private AudioFormat getAudioFormat() {
    float sampleRate = 8000.0F;
    //8000,11025,16000,22050,44100
    int sampleSizeInBits = 8;
    //8,16
    int channels = 1;
    //1,2
    boolean signed = true;
    //true,false
    boolean bigEndian = false;
    //true,false
    return new AudioFormat(
    sampleRate,
    sampleSizeInBits,
    channels,
    signed,
    bigEndian);
    }//end getAudioFormat
    public static void setCommunicatorIP(String communicatorIP) {
    MicrophoneManager.communicatorIP = communicatorIP;
    @Override
    public void run() {
    try {
    AudioFormat audioFormat = getAudioFormat();
    DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat);
    TargetDataLine targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
    targetDataLine.open(audioFormat);
    targetDataLine.start();
    ArrayList<Byte> byteArrayList = new ArrayList<Byte>();
    byte tempBuffer[] = new byte[10000];
    byteArrayOutputStream = new ByteArrayOutputStream();
    Thread mcThread = new Thread(new MicrophoneCommunicator());
    mcThread.start();
    //bos = new BufferedOutputStream(byteArrayOutputStream);
    while (!interrupt) {
    while (byteArrayList.size() < 10000) {
    targetDataLine.read(tempBuffer, 0, tempBuffer.length);
    for (byte b : tempBuffer) {
    byteArrayList.add(b);
    byte[] writerArray = new byte[byteArrayList.size()];
    tempBuffer = new byte[10000];
    for (int i = 0; i < byteArrayList.size(); i++) {
    writerArray[i] = byteArrayList.get(i);
    byteArrayList.clear();
    byteArrayOutputStream.write(writerArray, 0, writerArray.length);
    targetDataLine.close();
    } catch (Exception e1) {
    global.debug(e1);
    private class MicrophoneCommunicator implements Runnable {
    public void run() {
    try {
    Socket microphoneSocket = new Socket(communicatorIP, 5751);
    BufferedOutputStream netStreamOut = new BufferedOutputStream(microphoneSocket.getOutputStream());
    while (!interrupt) {
    if (byteArrayOutputStream.toByteArray().length >= 10000) {
    netStreamOut.write(byteArrayOutputStream.toByteArray());
    byteArrayOutputStream.reset();
    microphoneSocket.close();
    } catch (Exception e1) {
    global.debug(e1);
    }Now, here is the other code.
    public class Microphone implements Runnable {
    public void run() {
    try {
    byte[] tempArray = new byte[10000];
    ServerSocket micSocket = new ServerSocket(5751);
    micSocket.setSoTimeout(0);
    Socket microphoneSocket = micSocket.accept(); //Now connected
    BufferedInputStream bis = new BufferedInputStream(microphoneSocket.getInputStream());
    ByteArrayInputStream bais = new ByteArrayInputStream(tempArray);
    AudioFormat audioFormat = getAudioFormat();
    AudioInputStream audioInputStream =
    new AudioInputStream(bais,
    audioFormat,
    tempArray.length / audioFormat.getFrameSize());
    DataLine.Info dataLineInfo =
    new DataLine.Info(
    SourceDataLine.class,
    audioFormat);
    SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(
    dataLineInfo);
    sourceDataLine.open(audioFormat);
    sourceDataLine.start();
    ArrayList<Byte> byteArrayList = new ArrayList<Byte>();
    boolean interrupted = false;
    while (!interrupted) {
    int nextByte = 0;
    while ((nextByte = bis.read()) != -1 && (byteArrayList.size() < 10000)) {
    byteArrayList.add((byte) nextByte);
    for (int i = 0; i < byteArrayList.size(); i++) {
    tempArray[i] = byteArrayList.get(i);
    byteArrayList.clear();
    sourceDataLine.write(tempArray, 0, tempArray.length);
    interrupted = global.micInterrupt;
    microphoneSocket.close();
    micSocket.close();
    sourceDataLine.close();
    } catch (Exception e1) {
    e1.printStackTrace();
    private AudioFormat getAudioFormat() {
    float sampleRate = 8000.0F;
    //8000,11025,16000,22050,44100
    int sampleSizeInBits = 8;
    //8,16
    int channels = 1;
    //1,2
    boolean signed = true;
    //true,false
    boolean bigEndian = false;
    //true,false
    return new AudioFormat(
    sampleRate,
    sampleSizeInBits,
    channels,
    signed,
    bigEndian);
    }//end getAudioFormat
    }If you guys have any ideas on how to make this smoother... please feel free... Also, please feel free to use this code however you wish. I'd really appreciate this... It's hard for people to communicate when it's so choppy this way.
    However, the stream is currently only one way though, it only goes from one system to another... not two-way. One talks, the other types... it's complicated, but just might be useful info.
    Both sides are communicating via lan... so speed of connection isn't an issue...
    Thanks in advance.
    Best,
    Chris

    I'd recommend using UDP streams instead of TCP streams, and I'd recommend discarding out-of-order packets and packets that are delayed beyond a certain threshold (which you can play with)...

  • Send email with html and images over Sockets

    Hi! I'm sending email messages through sockets with html. So far is working great. But now, I need to include images in the html code, like a web page. I don't have any idea on how to do this. Sending image apart from the html code is not big deal, but how to put it in the code. I mean how to make this html code, work:
    <table border="0">
         <tr>
              <td>Image in code</td>
         </tr>
         <tr>
              <img src="what to put here"/>
         </tr>
    </table>This is the code that I'm using to send the html mail:
    StringBuffer retBuff = new StringBuffer();
              //BufferedReader msg;
              //msg = new BufferedReader(msgFileReader);
              smtpPipe = new Socket(mailHost, SMTP_PORT);
              smtpPipe.setSoTimeout(120000);
              if (smtpPipe == null) {
                   return retBuff;
              inn = smtpPipe.getInputStream();
              outt = smtpPipe.getOutputStream();
              in = new BufferedReader(new InputStreamReader(inn));
              out = new PrintWriter(new OutputStreamWriter(outt), true);
              if (inn == null || outt == null) {
                   retBuff.append("Failed to open streams to socket.");
                   return retBuff;
              String initialID = in.readLine();
              retBuff.append(initialID);
              retBuff.append("HELO " + localhost.getHostName());
              out.println("HELO " + localhost.getHostName());
              String welcome = in.readLine();
              retBuff.append(welcome);
              retBuff.append("MAIL From:<" + from + ">");
              out.println("MAIL From:<" + from + ">");
              String senderOK = in.readLine();
              retBuff.append(senderOK);
              for (int i = 0; i < to.length; i++) {
                   retBuff.append("RCPT TO:<" + to[i] + ">");
                   out.println("RCPT TO:<" + to[i] + ">");
                   String recipientOK = in.readLine();
                   retBuff.append(recipientOK);
              retBuff.append("DATA");
              out.println("DATA");
              out.println("From: Steren <" + from + ">");
              out.println("Subject: " + subject);
              out.println("Mime-Version: 1.0;");
              out.println("Content-Type: text/html; charset=\"ISO-8859-1\";");
              //out.println("Content-Type: multipart/mixed; charset=\"ISO-8859-1\";");
              //out.println("Content-Transfer-Encoding: 7bit;");
              //String line;
              //while ((line = msg.readLine()) != null) {
              //     out.println(line);
              out.println(msg);
              retBuff.append(".");
              out.println(".");
              String acceptedOK = in.readLine();
              retBuff.append(acceptedOK);
              retBuff.append("QUIT");
              out.println("QUIT");
              return retBuff;

    Throw all this away and use one of the numerous existing Java mail packages, such as javax.mail for a start.

  • Synchronizing peers in transfer over Socket

    Hi again!
    I'm relatively new to Java, so there are many issues I still have to figure out ;-)
    Here are two of them:
    1) How can peers be synchronized in transfer over Socket? For example:
    This is the receiving peer:
    DataInputStream dsin = new DataInputStream(socket.getInputStream());
    String s = dsin.readUTF();This is the sending peer:
    DataOutputStream dsout = new DataOutputStream(socket.getOutputStream());
    dsout.writeUTF("something...");
    dsout.close();At the receiving peer in some cases the EOFException or SocketException (Socket closed) are raised. I suspect this happens either because the receiver tries to read input before it is fully transfered or when the sender already managed to close the socket's OutputStream.
    So how can such a transfer be synchronized?
    2) What if both peers close their socket's OutputStream? Does this result in closing the connection and releasing all its resources, such as port?
    Thank you everyone!

    this is what I learnt:Sorry, try again!
    DO NOT close the Socket on any endpoint until you make sure that the other endpoint managed to call socket.getInputStream().This 'rule' is quite unnecessary.
    According to the documentation, getInputStream() may return a stream which buffer was discarded by network software if a broken connection was detected.That's a complete misreading and misquoting of the documentation. A reset can happen to the connection at any time; can cause loss of data from te socket receive buffer; and has nothing to do with the operation of getting the input stream. Getting the input stream of a socket has nothing to do with the network or the state of the connection. It just constructs a Java object. So this rule is quite pointless.
    Even more, it seems to be a good practice not to close the Socket until you are sure that the other endpoint will not try to read from the channel.You've got that back to front as well. THink about that some more and you will see it involves an infinite regression.
    The only rules you need are these:
    (a) don't close the socket until you're sure the other end has finished writing. You have to close the socket while the other end is still reading, so that it will get a EOS indication, so it will know you've gone away, so it will stop writing and close its end of the socket.
    (b) closing the socket or either of its streams closes the other two items. You should always close the topmost output stream of a socket and nothing else.

  • JSF and Double Byte Character

    Hi,
    I wanted to know how to handle <h:outputText> with chinese character or double byte character.
    See sample code below :
    <%@ page language="java" contentType="text/html; charset=UTF-8"      pageEncoding="UTF-8"%>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <h:form styleClass="form" id="form1">
    <% request.setCharacterEncoding("UTF-8"); %>
    <h:inputText styleClass="inputText" id="text1"></h:inputText>
    <hx:commandExButton type="submit" value="Submit" styleClass="commandExButton" id="button1"      action="#{pc_SubmitTest.doButton1Action}"></hx:commandExButton>
    <h:outputText styleClass="outputText" id="text2"></h:outputText>
    </h:form>
    When you input with double byte character and submit,
    the output screen value did not render properly .
    I tried this similiar code at JSP, it work fine.
    Anybody know how to solve this problem ?
    Anything need to do at pagecode level ?
    Thank you.
    Reinardy

    Problem was due to the fact that I was trying to generate the excel file in char stream instead of byte stream

  • Problem in character stream...sound is distorted

    hi friends,
    I have made a file copy program on audio file(mp3).
    its likely succeeded but the destination file give the distorted sound. I have used the character stream to make it done.
    however, it was not a problem using byte streams before few days.
    below is program
    import java.io.*;
    public class CopyBytes {
        public static void main(String[] args) throws IOException {
            BufferedReader in = null;
            BufferedWriter out = null;
            char []buff=new char[20000];
            int ch=0,length=30;
            try {
                in = new BufferedReader(new FileReader("1.mp3"));
                out = new BufferedWriter(new FileWriter("2.mp3"));      
              for(;ch!=-1;)
                while ((ch=in.read(buff,0,20000))!=-1) {
                      //System.out.format("%s\n\n break\n",new String(buff));
                      out.write(buff,0,20000);
                       break;               
            } finally {
                if (in != null) {
                    in.close();
                if (out != null) {
                    out.close();
    }although there was not use of two loops, actually i was making file splitter program and got this situation accordingly
    any analysis on distorted sound?

    san_4u wrote:
    I have used the character stream to make it done.Why? Clearly, you are not working with text files, so you shouldn't use FileReader/FileWriter at all, but work with streams and bytes. AFAIK, FileReader/FileWriter may perform special operation on the input/output due to character encodings, which you definitely don't want to happen with non-text files (as e.g. MP3 encoded audio files).

  • Filetransfer over sockets

    hi,
    im currently working on a filetransfer over sockets. this is what i do:
    i have a connection from the client to the server. on both sides i have a PrintStream for the output and a bufferedReader to read the responses. the client asks for a file and the server answers with the md5-hash size of the file, so that the client knows how many bytes it has to read. that works fine.
    now the filetransfer:
    the server writes the bytes of the file directly to the OutputStream (not the PrintStream). the client opens a BufferedInputStream on the mentioned socket and reads in as many bytes, as the server said before.
    now the problem:
    sometimes the filetransfer works fine, but sometimes some bytes are missing. i wonder where they are gone. it cant be a problem with the flush() method, because im using OutputStream to send the data. (i tested BufferedOutputStream with flush() with the same results).
    maybe it's not working because a attached a BufferedReader and a BufferedInputStream to the InputStream on the client-side...
    does anybody know, whats going wrong?
    let me know if you want to see some code.
    greetings,
    henrik

    i have solved this problem by using java.nio

  • URGENT : Pass non-serializable objects over sockets

    I am working with a non-serializable class.I can't change it to serializable(since it's an API class).I can't create a subclass either as I need to pass the same exact Object .I have tried wrapping it in a serializable class (as transient )but then the particular object that I need is not serialized.Is there a way to pass non-serializable objects over sockets?.Some other way of doing this?. Should i use RMI or Externalize?. Any help would be appreciated.

    {snip}
    Like this:
    public class SerializableLibraryClass extends
    LibraryClass implements Serializable {
    }Then you've got a class that is exactly the same as
    LibraryClass, but is now serializable.Not quite. The base class still isn't Serializable. Take, for example, the following code:
    public class A
        public int a1;
    public class B extends A implements Serializable
        public int b1;
    B beforeSend = new B();
    beforeSend.a1 = 1;
    beforeSend.b1 = 2;
    objectOutputStream.writeObject(b);
    B afterSend = (B)(objectInputStream.readObject());Both beforeSend and afterSend have fields a1 and b1. For beforeSend, a1 = 1 and b1 = 2. For afterSend, b1 = 2 but a1 = 0. The superclass wasn't Serializable; therefore, its members weren't Serialized and, when the object was created on the other side of the stream, a1 was left at its initial value.
    In short, you can't just Serialize the subclass. That Serialization won't apply to its superclasses.

  • Multible I/O Streams on Socket

    tachwohl
    How can a Server send multible I/O Stream to a single User at the same time?
    Ok, I have the following problem. This days, I'm coding a Client/Server Application. The Client/Server Connection is "should" be static during runtime.
    The Server and the application should be possible sends and recieves Objects all the time.
    The Client have a Socket, whitch connects to the Server. After connecting, the Server creates a InputStream and OutputStream and the Client has to buid a InputStream and a OutputStream right?
    After this, when my Client want to send or recieve something, I have to use the I/O Streams and socket created before, right?
    The Problem now, wenn I Stream one Object at the time through the I/O Stream, all works fine.
    But when my Server starts beeing Multithread, sending more than one object to the client (per thread started I/O Stream), I can't read the Input on the pipes end.
    What's the solution? Always creating a new I/O Stream? Working with SocketChannel (Non Blocking I/O)?
    plz need help
    thx

    I see, I have to do the OutputStreams one after one, right?
    Isn't there any way to create multible "outputpipes" over one socket at the same time?

  • Labview connect over sockets with php

    Hello, i´ve a simply led.
    I would control value of led over sockets using PHP programming language. My question is, where are documentation and examples? I found many examples between 2 or more Labview applications but not in PHP. I don´t found documentation that explins information to send to Labview application from PHP sockets...
    It´s possible? 
    Thanks!

    Hello, it work! I changed the number of bytes that TCP READ read. When string is equals "a", it set led to true:
    PHP Code:
             $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
            socket_bind($socket, "127.0.0.1");
            socket_connect($socket, "127.0.0.1", 4005);
            if(strcmp($data,"")==0){
                $msg = "Default msg";
            } else {
                $msg = $data;
            $size = strlen($msg);
            $sock_data = socket_write($socket, $msg, strlen($msg));
            $res = "Data sended ($size) with response $sock_data.";
    But now, a get this error when TCP close:
    But i don´t understand because i´ve defined my IP in VI Server:Machine Access .
    Any idea?

Maybe you are looking for

  • Very strange bug when using a view with a date

    Hi, Just thought I'd point out this bug I'd found and see if anybody has had similar problems. I'm connecting to Oracle 9i from servlets using the thin client-side JDBC driver. In the Oracle schema I've got a few views to another schema set up. One o

  • IMac problem with Lion.

    Just installed Lion on iMac 2.66 GHz Intel Core 2 Duo, 4GB 1067 MHz DDR3. How do i get System Information to run? Won't load from More Info..., won't load with option Apple, and won't load from Utilities?

  • Disable button when no records in multirecord block.

    Hello, In a tabular multirecord block we have a button that will open another window for the selected row. The problem is that when there are no records in the multirecord-block, the first line is still selected, and the pushbutton is enabled. This w

  • Time Machine Error Messages-HELP!!

    I purchased a Time Machine a few months ago and it worked for a little while. Now I just receive error messages: "Time Machine Error The backup disk image could not be mounted" and "The storage location for Time Machine backups can't be found". I can

  • Program not responding, webpage not responding

    Lately when ever I am in Internet Exlorer 9, I often get "webpage" not responding. Webpage being whatever web page I am viewing. It also does it sometimes when I am using certain programs like Word, etc. It will eventually unfreeze, but it takes a co