Java sockets (peek functionality)

Hi,
how do i peek at a datagram, look into the data and accordingly
decide whether to consume that datagram or leave it for later
processing?
Is this something Java sockets readily support OR do I need
to implement some kind of store-for-later-processing
please help
Thanks.

java.net.DatagramSocket doesn't have peek support in the API at this time - see 4102648.
If you were to use a non-blocking DatagramChannel and register it with a Selector then you should be notification that a packet can be read. Okay, it doesn't give you the details - just that a packet is available but it may help in your environment.

Similar Messages

  • Is is possible to create Socket using Java Stored Procedures/Function(Ora)?

    Hello Friends,
    Is is possible to create Socket using Java Stored Procedures/Function in Oracle?
    OR
    How I can send a message from oracle to Java Desktop Application which is working like server program?
    Please Guide !!

    J3Ganesh wrote:
    Hello Friends,
    Is is possible to create Socket using Java Stored Procedures/Function in Oracle?No, Oracle was very careful to take that feature out of the JDK provided in Oracle 10/11, but you can buy that feature back for, if I remember correctly, about 5000 dollars. (I actually raised a service request on this and then told my rep what I thought about the answer I received--some thing along the line of money grubbing so and so....)
    How I can send a message from oracle to Java Desktop Application which is working like server program?You can make a table and poll it from time to time from the Java side and write and commit what ever you want to the table. I do not know any way to send a signal from Oracle DB an external Java application--Java or PL/SQL stored procedure.

  • Socket AS3 ( Receive File .TXT ) + Java Socket

    Hi,
    I have Java Socket sending .TXT file ( 10 MB ) . But the AS3 only gets 63 Kb . I do not understand the loss of bytes ...
    Souce Java :
    public void sendFile(String fileName) {
            try {
                //handle file read
                File myFile = new File(fileName);
                byte[] mybytearray = new byte[(int) myFile.length()];
                FileInputStream fis = new FileInputStream(myFile);
                BufferedInputStream bis = new BufferedInputStream(fis);
                DataInputStream dis = new DataInputStream(bis);
                dis.readFully(mybytearray, 0, mybytearray.length);
                OutputStream os = clientSocket.getOutputStream();
                byte[] fileSize = intToByte(mybytearray.length);
                byte[] clientData = new byte[(int) myFile.length() + mybytearray.length];
                System.arraycopy(fileSize, 0, clientData, 0, fileSize.length); // Copy to the file size byte array to the sending array (clientData) beginning the in the 0 index
                System.arraycopy(mybytearray, 0, clientData, 4, mybytearray.length); // Copy to the file data byte array to the sending array (clientData) beginning the in the 4 index
                DataOutputStream dos = new DataOutputStream(os);
                //dos.writeUTF(myFile.getName());
                //dos.writeInt(mybytearray.length);
                dos.write(clientData, 0, clientData.length);
                dos.flush();
    AS3 Source..
    private function onResponse(e:ProgressEvent):void {
      var file:File;
      var fs:FileStream;
      var fileData:ByteArray = new ByteArray();
      file = File.documentsDirectory.resolvePath("tmpReceive.txt");
      fs = new FileStream();
      fs.addEventListener(Event.CLOSE,onCloseFileReceive);
    if(_socket.bytesAvailable > 0) {
      while(_socket.bytesAvailable) {
      // read the socket data into the fileData
      _socket.readBytes(fileData,0,0);
      fs.open(file, FileMode.WRITE);
      // Writing the file
      fs.writeBytes(fileData);
      fs.close();

    Crypto streams, like CipherInputStream andCipherOutputStream, do not behave properly until you
    issue a close() call. So if you are going to do
    crypto, you will need to trap the close() before it
    reaches the underlying socket streams. This is
    because the close() method finalizes the cryptographic
    operation. (Flush() would make more sense, no idea
    why they did it this way). You do want to finalize
    the crypto for any given message, but you need to trap
    the close() before it hits the socket and ends the
    whole affair.
    I don't see anything about that in the bug database.
    No matter what streams you are using, if you aregoing to keep the socket open for multiple
    request-response round-trips, you need to very closely
    pay attention to how much data is being sent on each
    trip. Normally, you can fudge this a bit on a
    request-response because the close() call on the
    output stream will cause the receiving input stream to
    behave more or less properly. However, a flush() will
    not.Why not? I use that all the time with no problem.
    A good practice is to send the content-length of
    the message first, so the receiving input stream
    "knows" when to stop reading, does not block, and then
    can send its own bytes back the other direction.
    (Where the process is repeated).
    An alternative is to use two threads: read and write.
    The read recieves, parses, validates and then pushes complete messages to a queue.
    The write pulls messages from the queue, processes and send a result.
    A variation to the above is what happens when an invalid message is received. The server can ignore it, the read can send a error response, or the read can push a message to the queue which causes the write to send a error response.

  • Java socket run on localhost against outside server

    Hi everyone,
    I am newbie to Java socket and networking. By spending this weekend over the internet reading and researching I have made my first Server-Client java socket program run sucessfully on my localhost 127.0.0.1. They can be connected and ok to communicate.
    However, when I put my server program to the LIVE server outside the network the client side says cannot connect to the server because: Connection Error, Connection refused: connect. So I read some stuff about firewall and NAT on the web but i was shamed that I don't understand there is any solution to this.
    It is great appreciated if someone can point me out how can I resolve this or make a step out because I am running out of time to give out the program against the deadline. But I really thank you anyone has been reading this.
    The server code:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package instantmessenger;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
        public class Server extends JFrame implements ActionListener {
            JTextArea textreceive   =new JTextArea();
            JTextArea textsend      =new JTextArea();
            JButton button          =new JButton("Send");
            BufferedReader in;
            PrintWriter out;
            public Server () {
                    //init   controls
                    setTitle("Server");
                    setBounds(50,50,500,400);
                    getContentPane().setLayout(null);
                    getContentPane().add(textreceive);
                    getContentPane().add(textsend);
                    getContentPane().add(button);
                    textreceive.setBounds(10,10,450,300);
                    textsend.setBounds(10,320,350,30);
                    button.setBounds(370,320,70,30);
                    button.addActionListener(this);
            public void listenClient() throws IOException {
                    ServerSocket   server=new   ServerSocket(9999);
                    System.out.println("start:"+server);
                    textreceive.append("start"+server+"\n");
                    try {
                            Socket s = server.accept();
                            try {
                                    System.out.println("connecting   :"+s);
                                    textreceive.append("connecting   :"+s+"\n");
                                    in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                                        out=new   PrintWriter(
                                        new   BufferedWriter(
                                        new   OutputStreamWriter(s.getOutputStream())));
                                    out = new PrintWriter(s.getOutputStream());
                                    String str=null;
                                    while(true) {
                                            str = in.readLine();
                                            System.out.println(str);
                                            textreceive.append(str+"\n");
                            finally {
                                s.close();
                    finally {
                        server.close();
            } // end function
            public void actionPerformed(ActionEvent event) {
                    String str = textsend.getText();
                    if( !str.equals("")) {
                            out.println(textsend.getText());
                            //out.println(textsend.getText());
                            out.flush();
                            textreceive.append(textsend.getText()+"\n");
                            textsend.setText("");
            } // end function
            public   static   void   main(String   args[])   throws   IOException {
                Server   s=new   Server();
                s.show();
                s.listenClient();
            } // end function
        } // end classThe client source code:
    package instantmessenger;
        import   java.net.*;
        import   java.io.*;
        import   javax.swing.*;
        import   java.awt.*;
        import   java.awt.event.*;
        public   class   Client   extends   JFrame implements   ActionListener {
            JTextArea   textreceive=new   JTextArea();
            JTextArea   textsend   =new   JTextArea();
            JButton     button   =new   JButton   ("Send");
            BufferedReader  in;
            PrintWriter     out;
            public Client(){
                    //init   controls
                    setTitle("Client");
                    setBounds(50,50,500,400);
                    getContentPane().setLayout(null);
                    getContentPane().add(textreceive);
                    getContentPane().add(textsend);
                    getContentPane().add(button);
                    button.addActionListener(this);
                    textreceive.setBounds(10,10,450,300);
                    textsend.setBounds(10,320,350,30);
                    button.setBounds(370,320,70,30);
           } // init
            public void startNet() throws IOException {
                  //Socket client=new Socket("localhost",9999);
                  Socket client=new Socket("222.33.444.5555",9999);  // NOT REAL SERVER IP
                  try {
                          System.out.println("Socket="   +client);
                          in    =   new BufferedReader(new InputStreamReader(client.getInputStream()));
                          out   =   new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);
                          String str=null;
                          while(true) {
                              str   =   in.readLine();
                              System.out.println(str);
                              textreceive.append(str+"\n");
                  finally {
                        client.close();
            } // end function
            public void actionPerformed(ActionEvent   event) {
                String str=textsend.getText();
                if(!str.equals("")) {
                    out.println(textsend.getText());
                    //out.println(textsend.getText());
                    out.flush();
                    textreceive.append(textsend.getText()+"\n");
                    textsend.setText("");
            } // function
            public static void main(String args[]) throws IOException {
                Client c=new Client();
                c.show();
                c.startNet();
            } // function
    } // end classThank you
    Morris Lee

    However, when I put my server program to the LIVE server outside the network the client side says cannot connect to the server because: Connection Error, Connection refused: connect. So I read some stuff about firewall and NAT on the web but i was shamed that I don't understand there is any solution to this.What do you want us to do? You already know that the problem probably is that you need to open port 9999 in the firewall, and you probably also need to configure it for port forwarding.
    Most clients will be able to connect after that, but some might still have problems. E.g. some companies don't allow clients to connect to other ports than a few well known ones (e.g. 21, 80 and 443)

  • Java user-defined function for mapping a complex structure

    All,
    Hope one of you can help me with this. I have a structure with over 15 fields and would like to concatenate all the fields into one target field and while I do this, I need to ensure that each field is padded with blanks as defined the data type. Can one of tell me if this is possible with a java user-defined function and if so, what type of logic is needed.
    Input_MT
    Field_1  string len=10 "need"
    Field_2  string len=6 "java"
    Field_3  string len=7 "help"
    Field_4  string len=8  "asap"
    etc,
    Output_MT 
    DataOut string  "need      java  help   asap    "
    (for some reason the exact spaces in between the words disappear in my Preview message)
    I have several fields in the input mt and therefore I find graphical mapping using concatenate and my own user defined function padWithSpace too messy.
    Thank you for you help.

    Hi,
    If your final req is to write all these fields next each other in a file, you can configure this in receiver file adapter by specifying the fixed length for each field.
    If you want the padded string as your MM o/p, you can create a simple user defined funtion with 15 fields as input and 15 constants for their lengths, and find out the length of the each string and pad it with required no of spaces.
    int max_len = 10;
    int actual_len;
    actual_len = a.lengh();
    for(int i=0; i < (max_len-actual_len; i++)
    a = a.append(" ");
    return a;
    praveen

  • Using plain Java Sockets(not RMI) how..?

    hi!
    1. Using plain Java Sockets(not RMI) how can the client detect when its server
    goes down?
    There is a long time interval between client requests and the client wants
    to retain a live connection rather than disconnect after every reqest.
    Please also cc your reply to [email protected]
    Thanks,
    \Raghu

    If you try to send data when the host is gone, it throws an exception. I don'thow to check if it is alive though. I'm having the same problem right now.

  • Java socket - unsure road to take!

    Hi all,
    We have an application requiring data transfer from a JSP Web application (socket client) and a stand-alone java application (socket server).
    This java stand-alone app communicates to an industrial microcontroller connected to the RS-232 serial port.
    When this java apps received a command from the JSP web app, it cannot service any other command from other uses, since there is just one RS-232 serial port on the computer. We would like to rely on the java & network environment to buffer additional commands receive simultaneously, as opposed to write code on the java socket server to handle this. In other works, our java stand-alone operates in an assynchronous, single-task mode.
    We are unsure which approach to take as far as java socket goes:
    1) simple socket server/client;
    2) multithread socket
    3) pooled
    Can anyone advise us.
    Thank you
    Trajano

    Hi Pete,
    1) Yes, we can have more than one user trying to access the micro-controllers, because we have in reality a network of micro-controllers connected to the single RS-232 computer port via a RS-485 to RS-232 converter;
    2) If a second user tries to issue a command to micro-controller, I would prefer for the java socket/environment to take care of the buffering, by just delaying the response, until the first user gets its command serviced
    3) If there is 1 user, him/her might issue several commands at the same time, by opening several JSP pages;
    4) No the controllers can service any instruction coming up at any time. The protocol is master/slave. The java app issues a request and the micro-controlle replies back and ready to accept any other request.
    ISSUE: My preference is for the system to take care of commands arriving at the socket server.
    This java app has two threads:
    1) Thread1 is the java socket server and upon receiving a command it will update three (3) properties:
    micro-controller address, command and product code
    2) Thread32 will be responsible for polling the 3 properties to check if they've changed. Upon detecting a change, it will build the data string and send to the RS-232 serial port.
    Any ideas/suggestions.
    Thanks in advance for any assistance.
    Regards

  • Java socket streams messing up

    iv wrote a games server and it uses java socket streams to send the messages back and forth between the game clients and the game server it self
    this all works great but when running and over about 5min its send over 1000 packets BUT
    it will crash iv found the reason is down to when reading the packets my parser is reading wrong part and grabbing a String part when it should be a INT
    now it should NEVER be reading this part of the packet so i put a trace on the packets coming in and ran it every packet was been read in perfect THEN just befor the crash TWO packets were merged together stright out from the socket stream this is y my packet reader was getting confused
    what im asking is can this happen in java sockets ? i thought they were bufferered so no matter how fast you send data it would always read it out in the same order ?? not sure how its merging these to packets
    is this possible of is my reader got an error in it altho works 95% of the time ??

    or do you have multiple buffered streams created from the same socket?

  • How to use java api for function activity in embed oracle workflow?

    because i can't install standalone oracle workflow successfully.
    pls tell me how to use java api for function activity in embed oracle workflow?
    are there some patch or pulg-in package?
    ths a lot...........

    The Java Function Activity Agent is not certified for Oracle Workflow embedded in Oracle Applications. Installing standalone workflow should be a lot easier than what you have found, although it looks like you did hit a Pentium 4 issue with the Oracle Universal Installer. I suggest you contact Oracle Support or Oracle Consulting for assistance.
    because i can't install standalone oracle workflow successfully.
    pls tell me how to use java api for function activity in embed oracle workflow?
    are there some patch or pulg-in package?
    ths a lot...........

  • JAVA SOCKET TIMEOUT WHEN GENERATING PDF TO ADS SERVER

    We are currently getting the error when attempting to generate the PDF from the thin portal BI Reports and recieved the JAVA SOCKET READ TIME OUT error and
    applied adjustments to the notes
    934725 and 826419 by changing the timeout sessions to 300, but still get the same timeout errors:
    Note: We changed ADUSER user type and password, passed rpcData test, RFC HTTP external connections to ADS server...so we've came a long ways and here we are now with the timeout errors...
    Any ideals???

    Hi
    when you reset password please select checkbox for password never expires.
    see the following notes :
    1.Note 944221 - Troubleshooting if problems occur in forms processing
    2.Note 811342 - Time Out exception when rendering to Adobe document service
    thanks
    Gopal

  • Java has no function level lock?

    Hi, everyone!
    I am a C++ programmer before and after reading the
    internal implemention method of Java Thread. I think
    Java has no function level lock and only object level
    lock. I mean to acquire a function lock is the same as
    acquire an object's lock.
    For example, when objectA.synchronizedFunctionA is called,
    suppose synchronizedFunctionA is a synchronized function of
    class A. Java only check whether objectA is locked. The synchronized
    function synchronizedFunctionA has no individual function level
    lock.
    Am I correct?
    If I am correct, I think in some certain application, function level
    lock will be more efficient than object level lock. Even though it
    should be used more carefully.
    Thanks in advance,
    George

    You could have a custom lock object for every method to get the same functionality.
    I.e. instead of...
    public synchronized void mySynchMethod() {
    }you'd do..
    public void mySynchMethod() {
       synchronize(thisMethodLock) {
    }where thisMethodLock would be some object used as a lock by only that method.

  • The service bit "write enable" in Java Socket

    Hello,
    I am trying to communicate with a third party application and I am having some problems. I use a standard Socket connection, were my application is the Server (ServerSocket). The connection is established, but no data is transmitted.
    I talked with the guys behind this third party application, and they said that perhaps their application does not receive a "write enable" service bit of the tcp/ip protocol. I'm not a network wiz, so this is an unknown territory for me.
    So I ask you. What is this "write enable" tcp/ip service bit? Is this per default on in java socket connections? If no, how can I change this?
    Perhaps this is very basic knowledge, but I've googled a bit and have not found this "service bit".

    This could refer to something in their
    protocol which you aren't implementing correctly.Probably, but I believe they have "forgotten" to mention that it is required in our implementation.
    OTOH if you are the server the transaction would
    normally begin with a request from the client, not a
    write-enablement from the server.The defined protocol smelled fishy when reading the "whitepaper", but we had to accept it (politics).

  • Java sockets forwarding (redirect)

    Dear all
    I’m try to write a java sockets program which will accept VNC connection and forward it to another pc that has VNC server installed.
    That is: a client use vnc viewer connect to a JavaServer(where the sockets program run), the JavaServer accept this connection and forward it to the VNC server
    The reason doing this is because the client can only connect to the JavaServer, and the JavaServer has the ability to connect any host.
    I can manage to initiate the connection, and give the password that the VNC server request with the following code, but after this just before the viewer start to show the remote desktop, the sockets stuck on reading.
    can anyone help me out please.
    public void listen() throws Exception
    ServerSocket server=new ServerSocket(443, 5);
    System.out.println("Start Listen ...");
    while(true)
    Socket serverCon=server.accept();
    System.out.println("get Connection from: "+serverCon.getInetAddress());
    InputStream serverIn=serverCon.getInputStream();
    OutputStream serverOut=serverCon.getOutputStream();
    Socket targetCon=new Socket("192.168.1.3", 5900);
    InputStream targetIn=targetCon.getInputStream();
    OutputStream targetOut=targetCon.getOutputStream();
    byte[] buf=new byte[10240];
    int len;
    while(true)
    len=targetIn.read(buf);
    System.out.println(len);
    serverOut.write(buf, 0, len);
    len=serverIn.read(buf);
    System.out.println(len);
    targetOut.write(buf, 0, len);
    }

    Hi EJP
    Thanks for your reply,
    I did try to use threads with pipeStream,
    but it’s worse than the simple one,
    since it cannot even initiate connect between two side,
    the following is the sample code I use, which I leaned from here http://home.tiscali.nl/bmc88/java/sbook/029.html
    I can't found any more info regard to this topic on the internet, can you give me a hint.
    thanks a lot.
    public void listen2() throws Exception
      ServerSocket server=new ServerSocket(443, 5);
      System.out.println("Start Listen ...");
      while(true)
       Socket serverCon=server.accept();
       System.out.println("get Connection from: "+serverCon.getInetAddress());
       InputStream serverIn=serverCon.getInputStream();
       OutputStream serverOut=serverCon.getOutputStream();
       Socket targetCon=new Socket("192.168.1.1", 5900);
       InputStream targetIn=targetCon.getInputStream();
       OutputStream targetOut=targetCon.getOutputStream();
       PipedInputStream serverPin=new PipedInputStream();
       PipedOutputStream serverPout=new PipedOutputStream(serverPin);
       PipedInputStream targetPin=new PipedInputStream();
       PipedOutputStream targetPout=new PipedOutputStream(targetPin);
       while(true)
        ReadThread rt=new ReadThread("reader", targetIn, serverPout);
        ReadThread wt=new ReadThread("writer", serverPin, serverOut);
        ReadThread rt2=new ReadThread("reader", serverIn, targetPout);
        ReadThread wt2=new ReadThread("writer", targetPin, targetOut);
        rt.start();
        wt.start();
        rt2.start();
        wt2.start();
    class ReadThread extends Thread implements Runnable{
      InputStream pi=null;
      OutputStream po=null;
      String process=null;
      ReadThread(String process, InputStream pi, OutputStream po)
       this.pi=pi;
       this.po=po;
       this.process=process;
      public void run()
       byte[] buffer=new byte[1024];
       int bytes_read;
       try
        for(; ; )
         bytes_read=pi.read(buffer);
         if(bytes_read==-1)
          return;
         po.write(buffer, 0, bytes_read);
       catch(Exception e)
        e.printStackTrace();
    }

  • C# socket and java socket

    hello
    i am a java programmer,recently we got a project,that need the c# app to communicate with java app ,i select the socket as intermediate.
    i notice that java socket term is divided into " blocking" and "non-blocking",the latter come from jdk1.4, the c# socket is devided into "synchronized" and "asynchronized" and both of them are blocking,
    in my project,i have tried synchronized c# socket coorperating to blocking java socket,it works well..but when i modify the c# app to ASYNCHRONIZED socket,my system DON'T works well,i don't know why? i can't find asynchronized socket in java,.i learn that nio socket is nonblocking, is it asynchronized?
    who can tell me what's is the best solution for the socket communication between java and c#?

    yes,i have read them,but it only tell me the communication between java apps,and DON'T tell me any clue about c# socket.

  • Java Sockets - help with using objects

    I am new to java sockets, and need to come up with a way to send a user defined instance of a class across a basic client/server application.
    I can not find out how to do this. I read the tutorials, but my class can not be serialized. How can I send/recieve this instance of a user defined class?

    right off the top of my head, doesn't serialver just spit out a UID for a given set of classes?
    To mark a class as Serializable, just implement the java.io.Serializable class - then you could use the readObject/writeObject methods of the ObjectInputStream/ObjectOutputStream classes.
    Good luck
    Lee

Maybe you are looking for

  • Error Message:  Sorry, a serious error has occurred that requires Adobe Premier Pro to shut down.

    Hi. I'm having another serious problem with CS4 (the version that comes with CS5 when you don't have 64 bit capability. I just finished a project, had saved it, and then had switched over to Adobe Encoder to create a finished flash video (which worke

  • Disappearing Sub Folders in Mail on my MAC

    Upgraded to X10 last night.  Today while filing email into sub folders, they disappeared from my view and I have not been able to find them again.  I have read all the postings but they have simply gone from view from any perspective on the computer.

  • One digit after the % in case of Turnover

    Hello All, Can anyone help me in following scenario-- I have two columns---- Turnover (in %) and Quantity with values as follows- Turnover(2009)- 4.898%, 3.916% etc.     Quantity (2009)- 2216.66, 9562.72 etc. Customer Requirement is 1 digit after the

  • Fire wire drive problem

    Hey all, I've got a problem when i plug in my firewire drive to my new MBP. It gives me the grey curtain of death. I've tried doing the usual like PVRAM and the PMU settings. It started when I was trying to add a partition to the drive using disk uti

  • How to show document title instead of file name in Document Manager

    In WebCenter Portal 11g PS5, there is the Document Manager task flow: http://docs.oracle.com/cd/E23943_01/webcenter.1111/e10149/content_doctf.htm#BABGAICC it displays a list of a Folder and its contents, much alike the output of the COLLECTION_DISPLA