Socket and 0x00 byte...

I've been working on some code to load data using the new
flash.net.Socket class, but I seem to have a problem with files
being sliced at '0x00' bytes...
For example, should I try to send (download) AA BB CC DD EE
FF 00 11 22, and then query the bytesAvailable, I get 6 as opposed
to 9, which is the actual packet size...
Is there a bug with the bytesAvailable getter? Or does the
socket close on ZERO/NULL bytes... perhaps it may be something
else?

Thank you. I have this. Now I would to ask, if it's good way or bad, because receiving side byte array correct receive and success save, because byte[] I am using for file. Problem I have with server, because throw exception --> image. How to repair it. I tried delete row with dos.flush(), but exception is the same. But row 84.
Error
// Sending side
          byte[] data = getByteArrayFromInputStream(inputStream);
          DataOutputStream dos = null;
          try {
               dos = new DataOutputStream(socket.getOutputStream());
               dos.writeInt(data.length);
               dos.write(data);
               dos.flush();
          } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
// Receiving side
     private void receiveFile() throws IOException {
          DataInputStream dis = null;
          dis = new DataInputStream(clientSocket.getInputStream());
          int length = dis.readInt();
          byte[] b = new byte[length];
          dis.read(b);
          dis.close();
Edited by: 893807 on 22.4.2012 8:06
Edited by: 893807 on 22.4.2012 8:11
Edited by: 893807 on 22.4.2012 8:12

Similar Messages

  • Need help on Socket and HTTP

    Hi,
    I need help ... please ... I have to use socket and not HTTPURLConnection
    I try to connect with a socket to a web server (apache2) and request one page but two times.
    The first time it works well but the second one it doesn't ... I get a null message.
    Why ?
    Does the server close the socket as soon as the page is sent ?
    If it doesn't how I can continue sending and receiving data on the same socket ?
    Here is my code:
    package test;
    import java.net.*;
    import java.io.*;
    public class Test
    private String laRequete = new String(
    "POST http://localhost:5577/Test/ HTTP/1.0\r\n"+
    "Host:localhost:5577\r\n"+
    "\r\n");
    PrintWriter laSortie;
    BufferedReader lEntree;
    Socket laSocketTCP;
    public Test()
    String tmp;
    try
    laSocketTCP = new Socket("localhost", 5577);
    laSortie = new PrintWriter(laSocketTCP.getOutputStream());
    lEntree = new BufferedReader(new InputStreamReader(laSocketTCP.getInputStream()));
    laSortie.println(laRequete);
    laSortie.flush();
    // Premier essai OK
    System.out.println(lEntree.readLine());
    while((tmp = lEntree.readLine()) != null)
    System.out.println(tmp);
    // Second essai => Not OK
    laSortie.println(laRequete);
    laSortie.flush();
    System.out.println(lEntree.readLine());
    while((tmp = lEntree.readLine()) != null)
    System.out.println(tmp);
    catch (Exception e)
    e.printStackTrace();
    public static void main(String args[])
    Test tp = new Test();
    Here is the result of the execution
    HTTP/1.1 200 OK
    Date: Wed, 29 Sep 2004 08:35:35 GMT
    Server: Apache/2.0.51 (Win32)
    Last-Modified: Wed, 29 Sep 2004 08:27:57 GMT
    ETag: "23a46-9a-56c93f9a"
    Accept-Ranges: bytes
    Content-Length: 154
    Connection: close
    Content-Type: text/html; charset=ISO-8859-1
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
    <HEAD>
    <TITLE> Index Test 1 </TITLE>
    </HEAD>
    <BODY>
    Test 1
    </BODY>
    </HTML>
    null
    Thanks, bye.

    Send an HTTP 1.1 request instead of a 1.0 request.
    HTTP 1.0 does not support keeping the connection open, so yes, the server closes the connection.
    Dave.

  • Writing to a socket appends random bytes to my message

    Hi Everyone,
    I'm a bit confused about this. I'm sending a byte array over a socket and when I read that array, I seem to always have 10 bytes appended to it. The 10 bytes are the same every time, which is really weird. I have looked all throughout my code in hopes of finding what is going wrong, but all I have discovered is that before I send the array over, those bytes are not there. As soon as I receive them, they appear.
    The environment I'm working in is Java on the client side (sending side) and C++ on the server side (receiving side). And no it's not the C++ side, that code has been in production for months and has never messed up.
    Thanks,
    Robbie

    So, don't post a lot of code. Just post a small amount of code. Boil the problem down to the smallest amount of code that will demonstrate the problem. In general, this is also a good way of debugging the problem in the first place. Just write a program to send a byte array. Like, 20 lines or something. Does it still show the problem? If so, post it here. If not, your problem lies elsewhere in your code.
    And use tags                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Simple question about sockets and streams - please answer it!

    Hi
    I have a server socket and a client socket. Both are up and runing. But I'm having problems to send a string from the client and read only the four first bytes on the server. Please read the code and some other comments below:
    socket client:
    DataOutputStream out =
    new DataOutputStream(socket.getOutputStream());
    // read from keyboard input
    BufferedReader myinput =
    new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Type any 4 chars and [enter].");
    String any = myinput.readLine();
    out.writeBytes(any);
    out.flush();
    server socket:
    in = new DataInputStream(socket.getInputStream());
    byte[] id = new byte[4];
    in.read(id, 0, 4);
    System.out.print(new String(id));
    According to the code, it should read 4 bytes from the input stream (in.read(id, 0, 4)), but it displays only the first byte. For example, if I type "hello" on client, the serve should show "hell" but it shows just "h"
    Any ideias? Thanks!

    Hi,
    Check the Javadoc for 'in.read(id, 0, 4);' This reads up to 4 bytes and returns the number of bytes read. You need something along the lines of
    int count = 0;
    while (count < 4)
    count += in.read(id, count, 4-count);
    Roger

  • Socket and Security Policy

    I've tried to set experiment with Socket communication in Flex, but I keep hitting problems. Approach 1: in a Flex web app, I load a crossdomain security policy from a server. I then open a socket and write a few bytes to the server. In my server, I do not get the expected output on the stream--in fact, I get nothing at all--until I close the Flex application, at which point I get a seemingly inifinite stream of the bytes '0xEFBFBF'. Here's a hexdump view of a fragment of the data Flash Player sends to the server after I close the Flex app:
    00000130  ef bf bf ef bf bf ef bf  bf ef bf bf ef bf bf ef  |................|
    00000140  bf bf ef bf bf ef bf bf  ef bf bf ef bf bf ef bf  |................|
    00000150  bf ef bf bf ef bf bf ef  bf bf ef bf bf ef bf bf  |................|
    Approach 2: I then tried it in air, but although the connection seems to initiate properly and I can go through the above trivial client-server interaction, after a few seconds, I get a SecurityErrorEvent. From what I've been able to follow of the docs, Air applications are trusted in this respect, and should not need to load security policy, right? I tried to add a call to Security.loadPolicy(), but it seems to be ignored. This is the message flow:
    Received [class Event] connect
    Received [class ProgressEvent] socketData
    Received [class Event] close
    Received [class SecurityErrorEvent] securityError
    Security error: Error #2048: Security sandbox violation: app:/main.swf cannot load data from localhost:5432.
    The Air version of my client code is below:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
            var str:Socket;
            private function handleClick(e:Event):void {
                Security.loadPolicyFile("xmlsocket://localhost:2525");           
                str = new Socket('localhost', 5555);
                var message:String = 'hello';
                for (var i:int = 0; i < message.length; i++) {
                    str.writeByte(message.charCodeAt(i));               
                str.writeByte(0);
                str.flush();
                str.addEventListener(Event.ACTIVATE, handleEvent);
                str.addEventListener(Event.CLOSE, handleEvent);
                str.addEventListener(Event.CONNECT, handleEvent);
                str.addEventListener(Event.DEACTIVATE, handleEvent);
                str.addEventListener(IOErrorEvent.IO_ERROR, handleEvent);
                str.addEventListener(ProgressEvent.SOCKET_DATA, handleEvent);
                str.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handleEvent);           
            private function handleEvent(e:Event):void {
                 trace("Received", Object(e).constructor, e.type);
                 if (e is ProgressEvent) {
                     var strBytes:Array = [];
                     while(str.bytesAvailable > 0) {
                         var byte:int = str.readByte();
                         strBytes.push(byte);
                     trace(String.fromCharCode.apply(null, strBytes));
                 } else if (e is SecurityErrorEvent) {
                     trace("Security error:", SecurityErrorEvent(e).text);
        ]]>
    </mx:Script>
    <mx:Button label="test" click="handleClick(event)"/>   
    </mx:WindowedApplication>
    The server is in Java and is as follows:
    import java.net.*;
    import java.io.*;
    public class DeadSimpleServer implements Runnable {
        public static void main(String[] args) throws Exception {
            if (args.length != 2) {
                throw new Exception("Usage: DeadSimpleServer policy-port service-port");
            int policyPort = Integer.parseInt(args[0]);
            int servicePort = Integer.parseInt(args[1]);
            new Thread(new DeadSimpleServer(policyPort,
                                            "<?xml version=\"1.0\"?>\n" +
                                            "<cross-domain-policy>\n" +
                                            "<allow-access-from domain=\"*\" to-ports=\"" + servicePort + "\"/>\n" +
                                            "</cross-domain-policy>\n"
                       ).start();
            new Thread(new DeadSimpleServer(servicePort, "world")).start();
            while (true) Thread.sleep(1000);
        private int port;
        private String response;
        public DeadSimpleServer(int port, String response) {
            this.port = port;
            this.response = response;
        public String getName() {
            return DeadSimpleServer.class.getName() + ":" + port;
        public void run() {
            try {
                ServerSocket ss = new ServerSocket(port);
                while (true) {
                    Socket s = ss.accept();
                    System.out.println(getName() + " accepting connection to " + s.toString());
                    OutputStream outStr = s.getOutputStream();
                    InputStream inStr = s.getInputStream();
                    int character;
                    System.out.print(getName() + " received request: ");
                    while ((character = inStr.read()) != 0) {
                        System.out.print((char) character);
                    System.out.println();
                    Writer out = new OutputStreamWriter(outStr);
                    out.write(response);
                    System.out.println(getName() + " sent response: ");
                    System.out.println(response);
                    System.out.println(getName() + " closing connection");
                    out.flush();
                    out.close();
                    s.close();
            } catch (Exception e) {
                System.out.println(e);
    Am I missing something? From what I understand, either of these approaches should work, but I'm stuck with both. I have Flash Player 10,0,15,3 and am working with Flex / Air 3.0.0 under Linux.

    So... apparently, with the Air approach, this is what I was missing: http://www.ultrashock.com/forums/770036-post10.html
    It'd be nice if FlashPlayer gave us a nicer error here.
    I'm still trying to figure out what the heck is going on in the web app (i.e., non-Air Flex) example. If anyone has any suggestions, that would be very helpful.

  • Transmitting AufioFormat Class and sampled bytes

    Hello everyone,
    I am building an audio server of sorts. The objective is something like this: the client makes a request which comprises of the filename that it wants served, and the maximum network bandwidth it wants to use for this music. upon receipt of this request, the server reads the audio in uncompressed form and decides on choice of algorithm it employs to compress the audio (along with sampling rate, sample resolution), then it tells the client about the encoding scheme it's employing to compress the subsequent audio then sends the audio packet by packet in same encoding scheme, until the client decides to change it's bandwidth specification (thus quality). when this happen, the server re-decides on encoding scheme and process repeats until the whole audio is played out.
    I have decided to run the server such that it creates a new thread for each client, and this thread handles the receipt of 'quality' packet and subsequent reading and compression. As of now i have already developed the classes that handle the various compression schemes, i have also written the codes for mutli-threaded server and client. (note: compression classes take raw bytes and compress them) and that's about it, rest of the job is yet to be done.
    What is the best way to handle this type of applications? Is EJB required for this? how to go about doing this? what are the best ways to extract only the audio bytes from a file ( and not the data about it's encoding scheme) what classes store it? how to make client aware of decoding schemes?
    PS: i'll provide any further relevant data and codes
    {here's the snippets from my implementation for some important aspects:
    my server which spawns new threads to serve.
    {code} try {
    ServerSocket serverSocket = new ServerSocket(902);
    while (true)
    new AudioServerThread(serverSocket.accept()).run();
    } catch .. { }
    the run method of the server thread: out = socket.getOutputStream();
    in = socket.getInputStream(); //both these within try catch.
    two methods in server thread ( write and read) handle the reading and writing to these streams and their error handling)
    Sorry for the long winded post like this one.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    thanks yet again, captfoss. i implemented many things u mentioned, it's working alright, but here, i'm hitting a roadblock that look like it'll be a big one ;-(.
    let me explain all that i have done:
    I have implemented the ServerServer class, which sits listening to requests to spawn new threads to services the client,
    the run method in ServerThread looks like this: (all the risky statements are in appropriate try catch blocks and
    SerializableAudioFormat is the class i taked about in prev post, it sends enough info over to the cleint for the client to re construct the audio format class )
              out = socket.getOutputStream();
            in = socket.getInputStream();soundFile = new File("C:\\welcome.wav");
            audioInputStream = AudioSystem.getAudioInputStream(soundFile);
            audioFormat = audioInputStream.getFormat();
            SerializableAudioFormat sf = new SerializableAudioFormat(audioFormat.getEncoding(), audioFormat.getSampleRate(), audioFormat.getSampleSizeInBits(), audioFormat.getChannels(), audioFormat.getFrameSize(), audioFormat.getFrameRate(), audioFormat.isBigEndian());
            Write(getBytes(sf));
            audioInputStream = AudioSystem.getAudioInputStream(soundFile);
            int nBytesRead = 0;
            byte[] abData = new byte[Main.BUFFER]; // BUFFER is declared in Main class
                             //as a final integer 10*1024*1024 which is 10 mega bytes.
            while (nBytesRead != -1) {
                    nBytesRead = audioInputStream.read(abData, 0, abData.length);
                if (nBytesRead >= 0) {
                    this.Write(abData);
                }and Write(byte[] b) wroks like with out.write(b) bmethod (out is o/p stream returned by the socket's getOutputStream() fn.)
    the byte[] getBytes(Object obj) method works like this:
    bos = new ByteArrayOutputStream();
                oos = new ObjectOutputStream(bos);
                oos.writeObject(obj);
                oos.flush();
                oos.close();
                bos.close();
    return bos.bos.toByteArray();////////////////////////////////
    All the try catch statements are eliminatd for readability.
    Client side a function playFromStream() works like this:
    byte[] buf = new byte[Main.BUFFER];   // BUFFER is declared in Main class
                        //as a final integer 10*1024*1024 which is 10 mega bytes.
    Encoding e = null;
            if(this.Read(buf) ==0)
                return;
            SerializableAudioFormat sf = (SerializableAudioFormat) toObject(buf);
            if (sf.int_encoding == 1)
                e=Encoding.ALAW;
             else if (sf.int_encoding == 2)
                e=Encoding.PCM_SIGNED;
             else if (sf.int_encoding == 3)
                e=Encoding.PCM_UNSIGNED;
             else if (sf.int_encoding == 4)
                e= Encoding.ULAW;
            audioFormat = new AudioFormat(e,
                    sf.sampleRate, sf.sampleSizeInBits,
                    sf.channels, sf.frameSize,
                    sf.frameRate, sf.bigEndian);
            SourceDataLine line = null;
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
            line = (SourceDataLine) AudioSystem.getLine(info);
            line.open(audioFormat);
            line.start();
            int nBytesRead = 0;
            while (nBytesRead != -1) {
                nBytesRead = Read(buf );
                System.out.println(nBytesRead);
                if (buf.length == 0) {
                    System.out.println("done");
                    break;
                } else {
                    line.write(buf, 0, nBytesRead);
            line.drain();
            line.close();Read function just reads from inputstream obtained from socket's getInpotStream() fn.
    and toObject function works like this:
    object = new java.io.ObjectInputStream(new java.io.ByteArrayInputStream(bytes)).readObject();and this object is returned
    the problem seems a little too big (pun unintended) when i run this program i get
    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at audiostream.Client.<init>(Client.java:23)
    at audiostream.Client.main(Client.java:35)
    Java Result: 1
    and when i decrease that buffer space to 1 MB the audio plays, but like a dog: I can hear a spasmodic fit that says "welcome to java multimedia programming", the audio plays in fits tht last about 500 milliseconds then halts for about a second and next 500ms plays and so on. The welcome.wav file is just 473KB and the whole audio lasts less than 3 seconds.
    god save me, what do i do?

  • Socket and keepalive

    How do I do keepalive with Flex sockets?

    Now this is client code. You should be having another piece of code that is
    listening on the IP, and port 8023. When you call socket.connect(ip, 8023); you
    connect to a machine running that piece of code typically called server. Tah
    code aknowledge the fact that you called connect and will send some answer back
    to you that you are connected. That answer will treigger your onConnect for
    which you registered with this line socket.addEventListener(Event.CONNECT,
    onConnect); Now you can send and recieve data.
    your onData will be called every time the application you connect to will send
    something to you.
    your onData should look something like this
    private function onData(event:ProgressEvent):void
                var data:ByteArray = readResponse();
                //do whatever you want with the bytes
    private function readResponse():ByteArray
                var byteArray:ByteArray = new ByteArray();
                socket.readBytes(byteArray, 0);   
                return byteArray;
    Your server will call you to ping it. So insetad of these lines
                //do whatever you want with the bytes
    you should read the bytes and somehow figure out that you need to ping. Then
    prepare a response message fluish the socket and wait.
    you should have a close handler also:
    socket.addEventListener(Event.CLOSE, closeHandler);
    private function closeHandler(event:Event):void
                trace("closeHandler: " + event);
                //if this code e4xecutes you are disconnected.
    http://livedocs.adobe.com/flex/3/html/help.html?content=17_Networking_and_communications_5 .html
    this also helps to get a better picture .
    C

  • Socket and multi-core troubles

    I have a 'hybrid' application as its refered to in the docs
    that I use to generate 3D scenes with the sandy flash library, and
    use those as motion graphics on top of a live video source for
    recording and broadcasting.
    The Camera sends hello to the flash socket, the flash app,
    draws the scene, the socket sends a byte array to the camera where
    it is alpha blended to into the live camera.
    On a single core system, there are no issues.
    On a dual core system, I do not get the whole byte array.
    Some how it seems in the middle of getting the bitmap to the array,
    something stops the writing and the socket is flushed anyway.
    I am receiving all 307200 bytes to the camera, but image is
    not fully drawn to the byte array. It results in a random
    quartering of the image, depending on how many bytes are actually
    sent.
    another behavior noted is when I drag the window, the socket
    still responds to the c++ code calling it, still sends 307200
    bytes, all '0''s, while nothing is drawn to bytes in the getPixels
    call.
    I can live with this behavior, but not the former.
    quote:
    //b bit mapdata, bytes is byte array
    b.draw(m_iDrawable);
    bytes=b.getPixels(new Rectangle(0,0,320,240));
    writeBytes(bytes,0,307200);
    flush();
    Is there any info regarding multi core processors
    interrupting drawing or socket communication? Even passing static
    bitmapdata that is never changes or displayed on the stage is
    interupted.
    The socket seems to be broken on the multicore machine.
    The c++ application that is creating the broadcast/file does
    receive the full frame buffer size, other wise it would hang until
    the full 307200 bytes are recieived. It appears that flash stops
    writing, and continues in the next call.
    There appears to be no handle to gauge how much data is
    actually passed to the byte array.
    I can set up live demos if desired.
    Single core machine and dual core machine running exact same
    software, and then stream the output graphics over rtmp.
    Help! Suggestions! Limiting the app to singe core machines is
    not an option!

    not Vista on the newer machine, right? (since Vista has
    TCP/IP stack problems)
    No, thanks.... Not vista. this is the working solution.
    quote:
    // in the enterframe event...
    do{}while(vidOut.m_bSharedState)
    // in the render event
    do{}while(vidOut.m_bSharedState)
    //this is in the function triggering the whole affair
    //Whether clone or lock is still nessecary I dont know
    if(fillBuffer)return;
    fillBuffer=true;
    if(!vidOut)return;
    do{}while(vidOut.m_bSharedState)
    vidOut.readBytes(new ByteArray(),0,vidOut.bytesAvailable);
    vidOut.draw(this.sprite());
    vidOut.flush();
    do{}while(vidOut.m_bSharedState)
    fillBuffer=false;
    //and this is the video out object's relevant function
    m_bSharedState=true;
    b=new BitmapData(320,240,true,0);
    b.lock();
    b.draw(p_iDrawable);
    var bmc:BitmapData=b.clone();
    bytes=bmc.getPixels(rec);
    bytes.position=0;
    writeBytes(bytes,0,307200);
    b.unlock(rec);
    m_bSharedState=false;
    Currently running at 15 fps encoding sesions with 0 drops as
    it should be.
    I'll throw up a temporary demo today in a bit.
    Thank you for your response!
    Solved

  • Conflict between socket and RMI

    Hi
    I wrote a program in client-server using socket and it was fine. I also wrote a client-server program using RMI. Fine as well. But after I connected the client-server using socket (open socket, send-receive messages, close socket), then use RMI. I got java.rmi.NotBoundException.
    Would anyone have a look and provide your feedback please? Thanks.
    big J
    *****************this is Server.java ***************************
    package single;
    import java.io.*;
    import java.rmi.Naming;
    import java.rmi.RemoteException;
    import java.net.*;
    import java.rmi.*;
    public class Server
    extends Thread {
    public static final int SOCKETPORT = 5555;
    private String serverName;
    public Server() throws IOException {
    System.out.println("*** socket opened ***");
    serverName = new String("localhost");
    ServerSocket serverSocket = new ServerSocket(SOCKETPORT);
    Socket socket = serverSocket.accept();
    InputStream is = socket.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
    System.out.println(bufferedReader.readLine());
    OutputStream os = socket.getOutputStream();
    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(os), true);
    printWriter.println("from server");
    os.close();
    is.close();
    socket.close();
    System.out.println("*** socket closed ***");
    public void runServer() {
    System.out.println("*** start of run():RMI ***");
    System.setSecurityManager(new SecurityManager());
    try {
    RMIInterfaceImpl rMIInterfaceImpl = new RMIInterfaceImpl();
    Naming.bind("//" + serverName + ":9999/RMIInterface", rMIInterfaceImpl);
    catch (RemoteException ex) {
    catch (MalformedURLException ex) {
    catch (AlreadyBoundException ex) {
    System.out.println("*** end of run():RMI ***");
    public static void main(String args[]) throws Exception {
    Server server = new Server();
    server.runServer();
    ******************this is Client.java **************************
    package single;
    import java.io.*;
    import java.net.*;
    import java.rmi.Naming;
    public class Client {
    private String serverName;
    private final static int SOCKETPORT = 5555;
    public Client() throws IOException {
    serverName = new String("localhost");
    Socket socket = new Socket(serverName, SOCKETPORT);
    OutputStream os = socket.getOutputStream();
    PrintWriter printWriter=new PrintWriter(os, true);
    printWriter.println("from client");
    InputStream is = socket.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
    System.out.println(bufferedReader.readLine());
    is.close();
    os.close();
    socket.close();
    public void runClient() throws Exception {
    System.out.println("*** start of runClient():RMI ***");
    System.setSecurityManager(new SecurityManager());
    RMIInterface rMIInterfaceImpl = (RMIInterface) Naming.lookup(
    "//" + serverName + ":9999/RMIInterface");
    String str = rMIInterfaceImpl.print();
    System.out.println(str);
    rMIInterfaceImpl.serverSide();
    System.out.println("*** end of runClient():RMI ***");
    public static void main(String args[]) throws Exception {
    Client client = new Client();
    client.runClient();
    ***************** this is RMIInterface.java ***********************
    package single;
    import java.rmi.Remote;
    import java.rmi.RemoteException;
    interface RMIInterface
    extends Remote {
    String print() throws RemoteException;
    void serverSide() throws RemoteException;
    ********************* this is RMIInterfaceImpl.java ***************
    package single;
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    public class RMIInterfaceImpl
    extends UnicastRemoteObject
    implements RMIInterface {
    public RMIInterfaceImpl() throws RemoteException {}
    public String print() {
    return new String("hello world");
    public void serverSide(){
    System.out.println("this should appear in serverside");

    I think you have a timing problem between your client and server. As soon as your client and server programs have finished their socket communication, they will both do their "runServer"/"runClient" methods. If the client attempts to lookup the server before the server has registered itself via Naming.bind(), I would expect that's why you're getting a NotBoundException in the client.
    You probably wouldn't use the design of your test client/server for something significant, but a quick and dirty way to make this work might be to have the client call Thread.sleep() for a few seconds before trying to do the lookup.

  • Problem with the socket and the standard output stream

    Hy, I have a little problem with a socket program. It has the server and the client. The problem is that the client at one point in the program, cannot print messages in the console.
    My program does the next: the server waits connections, when a client connects to it, the server gets outputstream to the socket and writes two strings on it. Meanwhile, the client gets the inputstream to the socket and reads on it with a loop the two strings written by the server . The strings are printed by the client in the console. The problem starts here; once the read strings are printed ,I mean, after the loop, there are other System.out.println in the client but the console doesnt print anything . It curious that only when I comment on the server code the line that says: "br.readLine()" just before the catch, the client prints all the System.out.println after the loop but why?
    Here is the code:
    Server code:
    public class MyServerSocket {
    public MyServerSocket() {
    try{
    ServerSocket server= new ServerSocket(2000);
    System.out.println("servidor iniciado");
    Socket client=server.accept();
    System.out.println("Client connected");
    OutputStream os=client.getOutputStream();
    PrintWriter pw= new PrintWriter(os);
    String cadena1="cadena1";
    String cadena2="cadena2";
    pw.println(cadena1);
    pw.println(cadena2);
    pw.flush();
    InputStream is=client.getInputStream();
    InputStreamReader isr= new InputStreamReader(is);
    BufferedReader br= new BufferedReader(isr);
    br.readLine(); //If a comment this line, the client prints after the loop, all the System.out....
    catch (IOException e) {
    // TODO: handle exception
    public static void main(String[] args) {
    new MyServerSocket
    Client code:
    public class MyClientSocket {
    public MyClientSocket () {
    try{
    Socket client= new Socket("localhost",2000);
    InputStream is=client.getInputStream();
    InputStreamReader isr= new InputStreamReader(is);
    BufferedReader br= new BufferedReader(isr);
    String read;
    while((read=br.readLine())!=null){
    System.out.println(read);
    //These messages are not printed unless I comment the line I talked about in the server code
    System.out.println("leido");
    System.out.println("hola");
    }catch (IOException e) {
    public static void main(String[] args) {
    new MyClientSocket
    }

    You are right but with this program the loop ends. As you see, the first class, the Server, writes to the socket one text file. The second class, the client, reads the text file in his socket written by the server and writes it to a file in his machine.
    NOTE: The loop in the client ends and the server doesnt make any close() socket or shutdownOutput() .
    public class ServidorSocketFicheromio {
         public ServidorSocketFicheromio() {
    try{
         ServerSocket servidor= new ServerSocket(2000);
         System.out.println("servidor iniciado");
         Socket cliente=servidor.accept();
         System.out.println("cliente conectado");
         OutputStream os=cliente.getOutputStream();
         PrintWriter pw= new PrintWriter(os);
         File f = new File("c:\\curso java\\DUDAS.TXT");
         FileReader fr= new FileReader(f);
         BufferedReader br= new BufferedReader(fr);
         String leido;
         while((leido=br.readLine())!=null){
              pw.println(leido);
         pw.flush();
         }catch (IOException e) {
         * @param args
         public static void main(String[] args) {
              new ServidorSocketFicheromio();
    public class ClienteSocketFicheromio {
         public ClienteSocketFicheromio() {
    try{
         Socket cliente= new Socket("localhost",2000);
         File f = new File("G:\\pepe.txt");
         FileWriter fw= new FileWriter(f);
         PrintWriter pw= new PrintWriter(fw);
         InputStream is=cliente.getInputStream();
         InputStreamReader isr= new InputStreamReader(is);
         BufferedReader br= new BufferedReader(isr);
         String leido;
         while((leido=br.readLine())!=null){
              pw.println(leido);
              System.out.println(leido);
              System.out.println("leido");
              System.out.println("hola");
              pw.flush();
         }catch (IOException e) {
         public static void main(String[] args) {
         new ClienteSocketFicheromio();/
    }

  • How to copy only part of a binary file after selecting a start and stop byte?

    I need to copy a selectable block of binary data from one file to a new file.  The binary file is made up of several data widths (8/16/32 signed and unsigned).  If I use a read binary function I will need to account for the data types within the file.  I was hoping to do a copy function with a start and stop byte control. Any pointers?  

    The attached Rube Goldberg Code copies two arrays of clusters to two arrays of indicators.
    Ben
    BTW: It does so by writtng the flattened data to a fixed length file and decoding same on the read.
    Message Edited by Ben on 03-24-2007 12:54 PM
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction
    Attachments:
    File Decode.JPG ‏137 KB
    FileDecode.vi ‏125 KB

  • Solution for Visual composer error: 32k span and 64k byte limit

    Dear friends,
    I am getting the error in visual composer 32k span and 64k byte limit since last half year,
    some time error will get resolved by adding layer in to model OR adding some table and form to model OR reduce the animation effect OR even by doing tab strip view for layer model, doing nested ivew.
    but this solution not usefull for every time.
    what should we do for this error(32k span and 64k byte limit),
    is it solved by updating EP version or by EP java stack or any other updates which will solve the This VC error.
    64k error i am getting is:
    +Error in compiling Flex application: Error: A function in the code exceeds the 64K byte limit (actual size = '65570'). Since the problem occurs in the compiler-generated deferred instantiation code, please refactor/componentize portions of this document.
          (/usr/sap/IBD/DVEBMGS10/j2ee/cluster/server0/GUIMachine_Business_Packages/Managment_cockpit11_31066/FLEX_COMPILATION_FOLEDR/AADCDM.mxml:19)
    Failed to compile AADCDM.mxml+
    hope to get answer form you,
    Thanks and Regards,
    Dushyant.

    Hi,
    I think it's better to post this question into the Visual Composer forum. Anyway, the 32k/64k bug is solved with the flex2 server which is already released.
    Also have a look into the [Wiki page|https://wiki.sdn.sap.com/wiki/display/VC/64Kbytelimit].
    Hope that helps!
    Best Regards,
    Marcel

  • Problems with sockets and InputsStreams

    Hi,
    I ve this code:
    InputStream is = null;
    boolean ok=true;
    while(ok){
    //sc is an object instance of socketConnection
    is = sc.openInputStream();
    return this.parse(is);
    //is.close();
    return "";
    and this exception is produced:
    java.io.IOException: no more Input Streams available.
    This exception is produced in the line:
    is = sc.openInputStream();
    I m connecting to a server and this server sends data throw a socket... but the problem is that when i m reading from this socket and this socket doesn t have data in it...
    how could i solve this problem...?
    Thanks,
    Diego

    That would be the "real" code:
    public String process()throws IOException{
    InputStream is = null;
    is = sc.openInputStream();
    String result= this.parse(is);
    is.close();
    any suggestions?
    Thanks,
    Diego

  • How to connect Master socket and extension to fibr...

    I have just had my fttp service enabled.
    I watched the online video on how to connect my phone, and it says that if you don't have the special socket that allows you to switch from copper to fibre, you should just connect the phne to the modem.
    I don't have the socket, just a normal phone socket right next to the modem.
    How do I connect my extensions? Can I just connect my modem to the socket and go from there, or do I need to do anything else?
    Sorry folks, I know very little about this stuff! 

    There is a guide here.
    http://bt.custhelp.com/app/answers/detail/a_id/37138/related/1
    My guess is that you would have to disconnect your extension wiring from the old master socket, and plug it into the Tel 1 socket via a phone splitter, if you need a phone near the fibre modem.
    There are a few other FTTP users on this forum, who may be able to give you more advice.
    There are some useful help pages here, for BT Broadband customers only, on my personal website.
    BT Broadband customers - help with broadband, WiFi, networking, e-mail and phones.

  • Implementing sockets and threads in a jframe gui program

    Hi, I am trying to find a solution to a problem I am having designing my instant messenger application.
    I am creating listening sockets and threads for each client logged into the system. i want to know if there is a way to listen to other clients request from the main gui and then if another client tries to establish a connection with me for example, a thread is created for that client and then my chat gui opens automatically has soon has the other client sends his or hers first text message to me.
    I am relatively new at socket programming has I am currently studying along this area. I know how to create threads and sockets but I am having trouble finding out a solution to my problem. Here is the code that I have done so far for the listening method from my main gui, and the thread class of what I have done so far.
    listening socket:
         private void listeningSocket()
                ServerSocket serverSocket = null;
                boolean listening = true;
                try
                    //listen in port 4444;
                    serverSocket = new ServerSocket(4444);
                catch(IOException x)
                    JOptionPane.showMessageDialog(null, "cannot listen to port 4444", null, JOptionPane.ERROR_MESSAGE);
                while(listening)
                    client_thread w;
                    try
                       w = new client_thread(serverSocket.accept(), jTextArea1);
                       Thread t = new Thread(w);
                       t.start();
                    catch(IOException x)
                         JOptionPane.showMessageDialog(null, "error, cannot start new thread", null, JOptionPane.ERROR_MESSAGE);
            }thread class:
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.sql.*;
    import java.awt.event.*;
    * @author jonathan
    public class client_thread extends Thread
         //define new socket object
        private Socket client_user = null;
        private JTextArea textArea;
        public client_thread(Socket client_user, JTextArea textArea)
            this.client_user = client_user;
            this.textArea = textArea;
        public void run()
            BufferedReader in = null;
            PrintWriter out = null;
            String error = "error has occured, messege was not sent";
            String messege = null;
             try
                //create input and output streams
                in = new BufferedReader(new InputStreamReader (client_user.getInputStream()));
                out = new PrintWriter(client_user.getOutputStream(), true);
                while(true)
                   //read messege sent by user
                   messege = in.readLine();
                    //display messege in textfield
                   out.println(messege);
                   textArea.append(messege);
            catch (IOException e)
                //error messege
                JOptionPane.showMessageDialog(null, error, null, JOptionPane.ERROR_MESSAGE);
    }

    Seems like all you need to do is create a new dialog for each socket that is established. Your current design looks like it will attempt to use the same textarea for all the sockets.
    I would say in your thread class do the following:
    MyConversationDialog dialog = new MyConversationDialog();
    while(true)
                   //read messege sent by user
                   messege = in.readLine();
                    //display messege in textfield
                   out.println(messege);
                   dialog.setVisible (true);
                   dialog.addMessage (message);
                }

Maybe you are looking for