Client-Server side GUI programming

I want to create a client-server side gui programming with java
i read this web adress
http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html
for information but there are some parts that i didnt understand and wait for your help
i m trying to build an online-help(live chat) system so when people press the start chat button a java page will appear but i wonder how this will connect to the person who is on server side
i mean is it possible to 2 users connect the same port and chat with each other
I mean when user press the chat button the online help supporter will be informed somebody wants to speak with him and they will start a chat
how can i do something like that
any help would be usefull thanks

Below is an example of a client/server program.
It shows how the server listens for multiple clients.
* TriviaServerMulti.java
* Created on May 12, 2005
package server;
* @author johnz
import java.io.*;
import java.net.*;
import java.util.Random;
* This TriviaServer can handle multiple clientSockets simultaneously
* This is accomplished by:
* - listening for incoming clientSocket request in endless loop
* - spawning a new TriviaServer for each incoming request
* Client connects to server with:
* telnet <ip_address> <port>
*     <ip_address> = IP address of server
*  <port> = port of server
* In this case the port is 4413 , but server can listen on any port
* If server runs on the same PC as client use IP_addess = localhost
* The server reads file
* Note: a production server needs to handle start, stop and status commands
public class TriviaServerMulti implements Runnable {
    // Class variables
    private static final int WAIT_FOR_CLIENT = 0;
    private static final int WAIT_FOR_ANSWER = 1;
    private static final int WAIT_FOR_CONFIRM = 2;
    private static String[] questions;
    private static String[] answers;
    private static int numQuestions;
    // Instance variables
    private int num = 0;
    private int state = WAIT_FOR_CLIENT;
    private Random rand = new Random();
    private Socket clientSocket = null;
    public TriviaServerMulti(Socket clientSocket) {
        //super("TriviaServer");
        this.clientSocket = clientSocket;
    public void run() {
        // Ask trivia questions until client replies "N"
        while (true) {
            // Process questions and answers
            try {
                InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
                BufferedReader is = new BufferedReader(isr);
//                PrintWriter os = new PrintWriter(new
//                   BufferedOutputStream(clientSocket.getOutputStream()), false);
                PrintWriter os = new PrintWriter(clientSocket.getOutputStream());
                String outLine;
                // Output server request
                outLine = processInput(null);
                os.println(outLine);
                os.flush();
                // Process and output user input
                while (true) {
                    String inLine = is.readLine();
                    if (inLine.length() > 0)
                        outLine = processInput(inLine);
                    else
                        outLine = processInput("");
                    os.println(outLine);
                    os.flush();
                    if (outLine.equals("Bye."))
                        break;
                // Clean up
                os.close();
                is.close();
                clientSocket.close();
                return;
            } catch (Exception e) {
                System.err.println("Error: " + e);
                e.printStackTrace();
    private String processInput(String inStr) {
        String outStr = null;
        switch (state) {
            case WAIT_FOR_CLIENT:
                // Ask a question
                outStr = questions[num];
                state = WAIT_FOR_ANSWER;
                break;
            case WAIT_FOR_ANSWER:
                // Check the answer
                if (inStr.equalsIgnoreCase(answers[num]))
                    outStr="\015\012That's correct! Want another (y/n)?";
                else
                    outStr="\015\012Wrong, the correct answer is "
                        + answers[num] +". Want another (y/n)?";
                state = WAIT_FOR_CONFIRM;
                break;
            case WAIT_FOR_CONFIRM:
                // See if they want another question
                if (!inStr.equalsIgnoreCase("N")) {
                    num = Math.abs(rand.nextInt()) % questions.length;
                    outStr = questions[num];
                    state = WAIT_FOR_ANSWER;
                } else {
                    outStr = "Bye.";
                    state = WAIT_FOR_CLIENT;
                break;
        return outStr;
    private static boolean loadData() {
        try {
            //File inFile = new File("qna.txt");
            File inFile = new File("data/qna.txt");
            FileInputStream inStream = new FileInputStream(inFile);
            byte[] data = new byte[(int)inFile.length()];
            // Read questions and answers into a byte array
            if (inStream.read(data) <= 0) {
                System.err.println("Error: couldn't read q&a.");
                return false;
            // See how many question/answer pairs there are
            for (int i = 0; i < data.length; i++)
                if (data[i] == (byte)'#')
                    numQuestions++;
            numQuestions /= 2;
            questions = new String[numQuestions];
            answers = new String[numQuestions];
            // Parse questions and answers into String arrays
            int start = 0, index = 0;
               String LineDelimiter = System.getProperty("line.separator");
               int len = 1 + LineDelimiter.length(); // # + line delimiter
            boolean isQuestion = true;
            for (int i = 0; i < data.length; i++)
                if (data[i] == (byte)'#') {
                    if (isQuestion) {
                        questions[index] = new String(data, start, i - start);
                        isQuestion = false;
                    } else {
                        answers[index] = new String(data, start, i - start);
                        isQuestion = true;
                        index++;
                start = i + len;
        } catch (FileNotFoundException e) {
            System.err.println("Exception: couldn't find the Q&A file.");
            return false;
        } catch (IOException e) {
            System.err.println("Exception: couldn't read the Q&A file.");
            return false;
        return true;
    public static void main(String[] arguments) {
        // Initialize the question and answer data
        if (!loadData()) {
            System.err.println("Error: couldn't initialize Q&A data.");
            return;
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(4413);
            System.out.println("TriviaServer up and running ...");
        } catch (IOException e) {
            System.err.println("Error: couldn't create ServerSocket.");
            System.exit(1);
        Socket clientSocket = null;
        // Endless loop: waiting for incoming client request
        while (true) {
            // Wait for a clientSocket
            try {
                clientSocket = serverSocket.accept();   // ServerSocket returns a client socket when client connects
            } catch (IOException e) {
                System.err.println("Error: couldn't connect to clientSocket.");
                System.exit(1);
            // Create a thread for each incoming request
            TriviaServerMulti server = new TriviaServerMulti(clientSocket);
            Thread thread = new Thread(server);
            thread.start(); // Starts new thread. Thread invokes run() method of server.
}This is the text file:
Which one of the Smothers Brothers did Bill Cosby once punch out?
(a) Dick
(b) Tommy
(c) both#
b#
What's the nickname of Dallas Cowboys fullback Daryl Johnston?
(a) caribou
(b) moose
(c) elk#
b#
What is triskaidekaphobia?
(a) fear of tricycles
(b) fear of the number 13
(c) fear of kaleidoscopes#
b#
What southern state is most likely to have an earthquake?
(a) Florida
(b) Arkansas
(c) South Carolina#
c#
Which person at Sun Microsystems came up with the name Java in early 1995?
(a) James Gosling
(b) Kim Polese
(c) Alan Baratz#
b#
Which figure skater is the sister of Growing Pains star Joanna Kerns?
(a) Dorothy Hamill
(b) Katarina Witt
(c) Donna De Varona#
c#
When this Old Man plays four, what does he play knick-knack on?
(a) His shoe
(b) His door
(c) His knee#
b#
What National Hockey League team once played as the Winnipeg Jets?
(a) The Phoenix Coyotes
(b) The Florida Panthers
(c) The Colorado Avalanche#
a#
David Letterman uses the stage name "Earl Hofert" when he appears in movies. Who is Earl?
(a) A crew member on his show
(b) His grandfather
(c) A character on Green Acres#
b#
Who created Superman?
(a) Bob Kane
(b) Jerome Siegel and Joe Shuster
(c) Stan Lee and Jack Kirby#
b#

Similar Messages

  • Establish a connection through RF modem's on client & server side & to set up PPP communication for data transfer

    hi
    can any1 over here help me out in how to establish connection between 2 RF modem's for data transfer , between client & server USing LABVIEW?
    I want to establish a connection between 2 PC's through  RF modem on client & server side & to set up PPP communication for data transfer.
    (I have tried data transfer through RS-232 using TCP/IP whn the 2 PC's are connected over ethernet... which is working.
    I also tried connecting loopback cable between 2 PC's COM port & geting data transfer using VIsa configure serial port & other visa functions  ... which is working)
    can u guide me how to establish connection between 2 RF modem's using LABview?
    & how does the data transfer take place between 2 RF modems through RS-232?
    is it using TCP/IP?
    If you got any links to go abt this issue do send me related links .. or any examples .....
    I am currently using Labview version 8.
    Waiting in anticipation.. reply ASAP..
    thanking you
    Regards
    Yogan..

    Howdy yogan,
    Maybe you could clarify a few things for me, and we'll see how we can help ya. TCP/IP protocol occurs through an ethernet connection; RS-232 communication occurs through an RS-232 serial connection, typically through a cable that has a DB9 connector on both ends. Do you mean that the RF modems in question have the option to communicate via RS-232 and/or via TCP/IP ethernet? Specific information like the manufacturer of your RF modems, the model number of your RF modems, and how you connect the modems to the PC would enable us to give you more efficient support.
    You can check our Instrument Driver Network (IDNet) to see if a plug-and-play/IVI driver already exists for your RF modem. (You'll need to know its manufacturer and model number.) In the case that you do find an IDNet driver for your modem, you can use this KnowledgeBase article for instructions on how to use the driver.
    Another excellent resource to consider is the NI Example Finder. You can access this within LabVIEW by navigating to Help»Find Examples and then searching for serial or TCP/IP examples.
    Message Edited by pBerg on 03-10-2008 04:35 PM
    Warm regards,
    pBerg

  • Client-Server side programing problem

    I designed a client-server program as seen below basis on serversocket and thread
    I use serversocket for making a host connection than people connect this socket via applet that i designed then they transffer data with socket.getInputStream() and socket.getOutputStream but it always happening between client and server how can i make theese streams transfer between clients is something like that possible if it is how?
    I couldnt send my hole java code because its too long and i wish i could explain my problem
        public void run()
            try
                servsocket = new ServerSocket(port);
                jTextArea1.append("Kullanici Girisi Bekleniyor.\n");
            catch(IOException e)
                jTextArea1.append("Sunucu Uzerinde Socket Acilamadi.\n");
                while(calisiyor)  //calisiyor variable is a boolean variable for checking if server is running
                    try
                    Socket sock = servsocket.accept();
                    background = new techsupportbackground(this,sock);
                    background.start();
                    catch(Exception e)
                        printstring("Hata:"+e);
                        break;
    this is the techsupportbackground classes run method it extends from thread
        public void run()
            if(!servicesetup()) return;
            support.printstring("Baglanti saglandi,kullanici basariyla giris yapti.");
            setPriority(MIN_PRIORITY);
            String sonmesaj = "";
            while(calisiyor)
                String mesaj = readinputline();
                if(mesaj == null) break;
                if (!sonmesaj.equals(mesaj))
                    support.printstring(username+"->"+mesaj);
                    sonmesaj = mesaj;
            cikis();
    and this is the client side program's run method
        public void run()
            try
                if(!doconnection())
                    client.printstring("Baglanti Saglanamadi:");
                    return;
            catch(Exception e)
                client.printstring("Baglanti Saglanamadi");
            while (calisiyor)
                String mesaj = readline();  //readline is the method which reads sockets input stream
                client.printstring(mesaj);
                    if (mesaj == null) break;
                    try {
                    Thread.sleep (client.timeupdate);
                    catch (InterruptedException e)
            if (server != null) closeserver();
            client.setdisconnected();
            client.printstring("Baglanti Koptu");

    I made two java file , one for server one for client
    server is working good openning the socket but the client is crashing when i attempt to connect to server
    here is my code if anyone could tell me where i made a mistake i would be very appreciate
    this is the client program
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.event.*;
    class client extends javax.swing.JFrame {
        private boolean baglandi;
        private MulticastSocket socket;
        private int port;
        private String ip;
        String username;
        private InetAddress group;
        private String msg;
        private DatagramPacket datawriter;
        private byte[] reader;
        private boolean calisiyor;
        private JScrollPane scrollpane;
        public client() {
            initComponents();
            this.setSize(490,450);
            jTextArea1.setEditable(false);
            jTextField2.setEditable(false);
            jButton2.setEnabled(false);
            jLabel3.setForeground(Color.RED);
            JPanel panel = new JPanel();
            panel.setLayout(new BorderLayout());
            panel.setBounds(0, 0, 480, 260);
            getContentPane().add(panel);
            scrollpane = new JScrollPane();
            scrollpane.getViewport().add(jTextArea1);
            panel.add(scrollpane,BorderLayout.CENTER);
            baglandi=false;
            ip="228.5.6.7";
            port=2222;
            try
            group = InetAddress.getByName(ip);
            msg ="";
            datawriter = new DatagramPacket(msg.getBytes(),msg.length(),group,port);
            calisiyor = false;
            catch(Exception e)
        private void initComponents() {
            jTextArea1 = new javax.swing.JTextArea();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jTextField1 = new javax.swing.JTextField();
            jTextField2 = new javax.swing.JTextField();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jButton3 = new javax.swing.JButton();
            jLabel3 = new javax.swing.JLabel();
            getContentPane().setLayout(null);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            getContentPane().add(jTextArea1);
            jTextArea1.setBounds(0, 0, 480, 260);
            jLabel1.setText("Kullanici Adi");
            getContentPane().add(jLabel1);
            jLabel1.setBounds(0, 270, 90, 15);
            jLabel2.setText("Mesaj");
            getContentPane().add(jLabel2);
            jLabel2.setBounds(0, 300, 60, 15);
            getContentPane().add(jTextField1);
            jTextField1.setBounds(100, 270, 290, 21);
            getContentPane().add(jTextField2);
            jTextField2.setBounds(100, 300, 290, 21);
            jButton1.setText("Gonder");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            getContentPane().add(jButton1);
            jButton1.setBounds(400, 270, 80, 25);
            jButton2.setText("Gonder");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
            getContentPane().add(jButton2);
            jButton2.setBounds(400, 300, 80, 25);
            jButton3.setText("Durdur");
            jButton3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton3ActionPerformed(evt);
            getContentPane().add(jButton3);
            jButton3.setBounds(400, 340, 80, 25);
            jLabel3.setText("Baglanti Saglanamadi");
            getContentPane().add(jLabel3);
            jLabel3.setBounds(0, 360, 130, 15);
            pack();
        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
            durdur();
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
            printoutput();
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            baslat();
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            new client().show();
        public void baslat()
            username = jTextField1.getText();
            try
                socket = new MulticastSocket(port);
                socket.joinGroup(group);
            catch(IOException e)
                jTextArea1.append("Guvenlik Engellemesi Sebebiyle Sunucuya Ulasilamadi.\n");
                return;
                    jTextArea1.append("Sunucuya Baglanildi");
                    baglandi = true;
                    calisiyor = true;
                    jLabel3.setText("Baglanti Saglandi");
                    jTextArea1.append("Sunucuya Basariyla Baglanildi\n");
                    jLabel3.setForeground(Color.GREEN);
                    jButton1.setEnabled(false);
                    jTextField1.setEditable(false);
                    jButton2.setEnabled(true);
                    jTextField2.setEditable(true);
                while (calisiyor)
                        String mesaj = readline();
                        printstring(mesaj);
                        if (mesaj == null) break;
        public void durdur()
            jTextField2.setEditable(false);
            jTextField1.setEditable(true);
            jButton2.setEnabled(false);
            jButton1.setEnabled(true);
            jLabel3.setText("Baglanti Saglanamadi");
            jLabel3.setForeground(Color.RED);
            try
                socket.leaveGroup(group);
            catch(Exception e)
        public void printoutput()
            try
            String mesaj = jTextField2.getText();
            jTextField2.setText("");
            writeline(username+":->"+mesaj);
            catch(Exception e)
                printstring("Veri Ulastirilamadi.");
        public void printstring(String s)
            jTextArea1.append(s+"\n");
        public void setdisconnected()
            jTextField2.setEditable(false);
            jTextField1.setEditable(true);
            jButton2.setEnabled(false);
            jButton1.setEnabled(true);
            jLabel3.setText("Baglanti Saglanamadi");
            jLabel3.setForeground(Color.RED);
            public String readline()
                byte[] buf = new byte[1000];
                DatagramPacket datapack = new DatagramPacket(buf,buf.length);
                try
                    socket.receive(datapack);
                    String mesaj = buf.toString();
                    return mesaj;
                catch(Exception e)
                    printstring("Sunucuya Ulasilamadi");
                    return null;
        public void writeline(String s) throws IOException
                try
                    msg = s;
                    socket.send(datawriter);
                    printstring(msg);
                catch(Exception e)
                    printstring("Mesaj ulastirilamadi.");
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton3;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JTextArea jTextArea1;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JTextField jTextField2;
        // End of variables declaration
    this is the server program
    import java.net.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class techsupport extends javax.swing.JFrame implements ActionListener,Runnable {
        private MulticastSocket servsocket;
        private int port;
        private boolean calisiyor;
        private JScrollPane scrollpane;
        private techsupportbackground  background;
        private InetAddress group;
        public techsupport(String title) {
            super(title);
            initComponents();
            this.setSize(400,400);
            port=2222;
            jTextField1.addActionListener(this);
            jButton1.addActionListener(this);
            calisiyor=true;
            jTextArea1.setEditable(false);
            JPanel panel = new JPanel();
            panel.setLayout(new BorderLayout());
            panel.setBounds(0,10,400, 230);
            getContentPane().add(panel);
            scrollpane = new JScrollPane();
            scrollpane.getViewport().add(jTextArea1);
            panel.add(scrollpane,BorderLayout.CENTER);
                try
                group = InetAddress.getByName("228.5.6.7");
                catch(Exception e)
        private void initComponents() {
            jTextArea1 = new javax.swing.JTextArea();
            jButton1 = new javax.swing.JButton();
            jLabel1 = new javax.swing.JLabel();
            jButton2 = new javax.swing.JButton();
            jTextField1 = new javax.swing.JTextField();
            getContentPane().setLayout(null);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            getContentPane().add(jTextArea1);
            jTextArea1.setBounds(0, 10, 400, 230);
            jButton1.setText("Start");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            getContentPane().add(jButton1);
            jButton1.setBounds(160, 260, 80, 25);
            jLabel1.setText("Port");
            getContentPane().add(jLabel1);
            jLabel1.setBounds(0, 240, 120, 15);
            jButton2.setText("Stop");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
            getContentPane().add(jButton2);
            jButton2.setBounds(250, 260, 90, 25);
            getContentPane().add(jTextField1);
            jTextField1.setBounds(0, 260, 130, 21);
            pack();
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
            try
            servsocket.close();
            jButton1.setEnabled(true);
            printstring("Port Kapatildi.");
            jTextArea1.setText("");
            catch(Exception e)
                printstring("Hata:"+e);
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
        public static void main(String args[]) {
            new techsupport("Teknik Destek Sunucu").show();
        public void actionPerformed(ActionEvent e) {
            boolean status = false;
            String komut = e.getActionCommand();
                if (komut.equals("Start"))
                    try
                        port = Integer.parseInt(jTextField1.getText());
                        jButton1.setEnabled(false);
                    catch(NumberFormatException err)
                        jTextArea1.append("Hatali Port Numarasi"+"\n");
                        jButton1.setEnabled(true);                   
                    Thread uygulama = new Thread(this);
                    uygulama.start();
                else if (komut.equals("Stop"))
                    calisiyor=false;
                    dispose();
        public void run()
            try
                servsocket = new MulticastSocket(port);
                servsocket.joinGroup(group);
                jTextArea1.append("Kullanici Girisi Bekleniyor.\n");
            catch(IOException e)
                jTextArea1.append("Sunucu Uzerinde Socket Acilamadi.\n"+e.toString());
        public void printstring(String s)
            jTextArea1.append(s+"\n");
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JTextArea jTextArea1;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration
    }

  • Client/Server in one program (using multiple threads)?

    Is there some examples out there of how to use a client and server in a single program using separate threads? Also, is it possible to start a third thread to control the packets, such as drop a random or specified number of packets (or match on specific data in a packet)?

    Just trying to have a client send udp packets to a server (all on the same machine running from the same program) and want to be able to drop packets coming from the client side to the server side.
    E.g.,
    Here's an example that I found here: http://compnet.epfl.ch/tps/tp5.html
    import java.io.<strong>;
    import java.net.</strong>;
    import java.util.<strong>;
    /</strong>
    * Server to process ping requests over UDP.
    public class PingServer {
         private static double lossRate = 0.3;
         private static int averageDelay = 100; // milliseconds
         private static int port;
         private static DatagramSocket socket;
         public static void main(String[] args) {
              // Get command line arguments.
              try {
                   if (args.length == 0) {
                        throw new Exception("Mandatory parameter missing");
                   port = Integer.parseInt(args[0]);
                   if (args.length > 1) {
                        lossRate = Double.parseDouble(args[1]);
                   if (args.length > 2) {
                        averageDelay = Integer.parseInt(args[2]);
              } catch (Exception e) {
                   System.out.println("UDP Ping Server");
                   System.out.println("Usage: java PingServer port [loss rate] [average delay in miliseconds]");
                   return;
              // Create random number generator for use in simulating
              // packet loss and network delay.
              Random random = new Random();
              // Create a datagram socket for receiving and sending UDP packets
              // through the port specified on the command line.
              try {
                   socket = new DatagramSocket(port);
                   System.out.println("UDP PingSever awaiting echo requests");
              } catch (SocketException e) {
                   System.out.println("Failed to create a socket");
                   System.out.println(e);
                   return;
              // Processing loop.
              while (true) {
                   // Create a datagram packet to hold incoming UDP packet.
                   DatagramPacket request = new DatagramPacket(new byte[1024], 1024);
                   // Block until the host receives a UDP packet.
                   try {
                        socket.receive(request);
                   } catch (IOException e) {
                        System.out.println("Error receiving from socket");
                        System.out.println(e);
                        break;
                   // Print the received data.
                   printData(request);
                   // Decide whether to reply, or simulate packet loss.
                   if (random.nextDouble() < lossRate) {
                        System.out.println("   Reply not sent.");
                        continue;
                   // Simulate network delay.
                   try {
                        Thread.sleep((int) (random.nextDouble() * 2 * averageDelay));
                   } catch (InterruptedException e) {}; // Ignore early awakenings.
                   // Send reply.
                   InetAddress clientHost = request.getAddress();
                   int clientPort = request.getPort();
                   byte[] buf = request.getData();
                   DatagramPacket reply = new DatagramPacket(buf, buf.length,
                             clientHost, clientPort);
                   try {
                        socket.send(reply);
                   } catch (IOException e) {
                        System.out.println("Error sending to a socket");
                        System.out.println(e);
                        break;
                   System.out.println("   Reply sent.");
          * Print ping data to the standard output stream.
         private static void printData(DatagramPacket request) {
              // Obtain references to the packet's array of bytes.
              byte[] buf = request.getData();
              // Wrap the bytes in a byte array input stream,
              // so that you can read the data as a stream of bytes.
              ByteArrayInputStream bais = new ByteArrayInputStream(buf);
              // Wrap the byte array output stream in an input stream reader,
              // so you can read the data as a stream of characters.
              InputStreamReader isr = new InputStreamReader(bais);
              // Wrap the input stream reader in a buffered reader,
              // so you can read the character data a line at a time.
              // (A line is a sequence of chars terminated by any combination of \r
              // and \n.)
              BufferedReader br = new BufferedReader(isr);
              // We will display the first line of the data.
              String line = "";
              try {
                   line = br.readLine();
              } catch (IOException e) {
              // Print host address and data received from it.
              System.out.println("Received echo request from "
                        + request.getAddress().getHostAddress() + ": " + line);
    }I'm looking to do the "processing loop" in a separate thread, but I'd also like to do the client in a separate thread
    So you're saying, just put the client code in a separate class and start the thread and that's it? As far as the packet rate loss thread, is this possible to do in another thread?

  • Problem client/server with GUI

    I have a problem with a project im working on. I have a main method that has an infinite loop but before it enters the loop, i draw the GUI. I put a simple print statement and found that it goes through the loop once. Can someone help me to figure out why the file does not send. I tried running this code without the GUI and the file sends.
    here is the code:
    public static void main(String[] args) {
              final String PATH = "/home/dford/Desktop/";
              ClientGUI display = new ClientGUI();
              try{
                   Download[] download = new Download[5];
                   int downloadIndex = 0;
                   ServerSocket welcomeSocket = new ServerSocket(9876);
                   while(true)
                        try{
                             Socket connectionSocket = welcomeSocket.accept();
                             if(downloadIndex < 5)
                                  download[downloadIndex++] = new Download(connectionSocket,
                                                                                     3334,
                                                                                     PATH + "snake.c");
                        catch(Exception e){}
                        System.out.println("Got here");
                        for(int i=0; i<downloadIndex; i++){
                             while(download.hasMore()){
                                  download[i].getNext();
              catch(Exception e){
                   System.err.println(e);
         }**And im trieing not to use Threads, but if i have to please let me know.
    Edited by: dford425 on Mar 18, 2008 8:03 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    nevermind, i figured it out

  • Disable ADF Client and Server side validation during drop down changes

    In my ADF Faces there is PanelFormLayout containing dropdown with country code value. Changing the dropdown value should change the layout to different country.
    If the data is proper in the form the Layout changes perfectly but if the data is not proper it gives client validation & the layout doesn't get changed.
    I want to disable the client/server side validation while changing the dropdown.

    Hi Just framing the Question once again -
    In my ADF Faces there is PanelFormLayout containing dropdown with country code value. Changing the dropdown value should change the layout to different country.
    If the data is proper in the form, the Layout changes perfectly but if the data is not proper it gives client validation & the layout doesn't get changed.
    I want to disable the client side validation just for that page or panelformLayout
    Issue -
    If the data is incorrect on the form, user is able to change the countrycode from the dropdown but the layout doesn't changes because client validation is stopping.
    Below is the code -
    1) Changing the drop down cause the switcher to call the code - defaultFacet="#{backingBeanScope.AddressComp.displayType}" which changes the layout.
    2) But if the data is not correct the country value is getting change with the new Country but the Layout is unable to get change. ADF start showing client validation.
    <af:panelGroupLayout id="pglA1" partialTriggers="plcol1:table1 *usCountryId caCountryId*">
         <af:switcher binding="#{backingBeanScope.AddressComp.switcherComp}" defaultFacet="*#{backingBeanScope.AddressComp.displayType}*">
              <f:facet name="US">
                   <af:panelFormLayout>
                        <af:selectOneChoice value="#{bindings.CntryCd.inputValue}" label="#{bindings.CntryCd.label}" required="#{bindings.CntryCd.hints.mandatory}"
         id="usCountryId" autoSubmit="*true*">
                        <f:selectItems value="#{bindings.CntryCd.items}" id="si14"/>
                   </af:selectOneChoice>
                   </af:panelFormLayout>
              </f:facet>
              <f:facet name="CA">
                        <af:panelFormLayout>
                        <af:selectOneChoice value="#{bindings.CntryCd.inputValue}" label="#{bindings.CntryCd.label}" required="#{bindings.CntryCd.hints.mandatory}"
         id="caCountryId" autoSubmit="true">
                        <f:selectItems value="#{bindings.CntryCd.items}" id="si14"/>
                   </af:selectOneChoice>
              </af:panelFormLayout>
              </f:facet>
         </af:switcher>
    </af:panelGroupLayout>

  • UIX - unable to turn off client and server side field validation

    Hello,
    I've scoured the forums for info on how to turn off client / server side field validation, for the very common case of a Cancel button. Here's the use case:
    User enters a page displaying records of some kind that can be edited, or an option to create a new one. User clicks create, is taken to a new data entry form. Before entering any data, the user decides he isn't interested, and clicks the cancel button.
    The problem I'm having is that I'm getting messages that required fields have no values. I have found several references on this forum that setting the submitButton attribute unvalidated="true" will turn off client side validation. Here's what my submitButton looks like:
    <submitButton text="Cancel" event="success" unvalidated="true"/>
    But I am still getting errors, such as:
    JBO-27014: Attribute ListName in DealerListAppModule.WebDlrListsView1 is required
    Now I have also seen references in the forums to turning off server side validation by overriding the validatModelUpdates method in the DataAction. I have done this too. No luck.
    Any ideas why this isn't working? I have seen other posts in the forums stating that there were improvements in JDev 10.1.2 that caused a create but not insert, where you could just navigate away from the page you were on, without having to worry about rolling back the create of a new record. I am also not seeing this behavior either. I am using 10.1.2, completely updated, but when I execute a create, if I navigate back from the create page to the original one without saving (i had to fool with this to get it to work because of the validation problems above), I am still seeing the blank, created record in my rowset. I originally created my project in 9.0.5.2, but am now using 10.1.2, and having migrated the project.
    So what's the deal? What's the definitive way to turn off both client side and server side validation, and what's the status of this create but not insert functionality?
    Brad

    Haven't worked with this but possibly this method of "deactivation" is not valid in 11gR2? Have you cross checked that with Oracle support?

  • JavaFX as a SaaS/ How good is it for Client-Server work?

    I was under the impression that FX could be used to produce a Client-Server application as well as SaaS.
    a member of another forum said "I'm sure you meant to say "Desktop". JavaFX will not be making inroads on the web as a client-side technology."
    To which I said
    There have been examples of FX used with EE
    http://www.oracle.com/technetwork/java/javafx/samples/index.html
    http://docs.oracle.com/javafx/2/overview/jfxpub-overview.htm
    Sales Dashboard (DataApp)
    DataApp is a client-server application for a fictional global automobile company called Henley Car Sales. Automobile sales are simulated on an EJB server using JavaDB, and the data is available via Derby and a RESTful web service. The client demonstrates a variety of data presentations by using a mix of FXML and JavaFX.
    I thought originally that JavaFX was "Desktop" only also, until I found this example. I couldn't get it to run due to some weird Database line read issue that others also had. I'm not sure if this is now due to FX's integration, or if this was something new, but I believe I have seen another FX client-server app as well.
    I'm not that familiar with the client-server side of Java yet, so if you have other Information I would like to know, because I am looking to design a Client-Server app with FX, and I don't see why it would be an issue, unless there are huge limitations."
    He ended up saying "Those are still desktop apps. Sure, they are client-server in that they connect to a remote database. But they are still traditional fat-client apps rather than web-based thin-client SAAS web applications which, these days, most people will think of when you say "client".
    My point is to be more precise when you use the word "client".
    But if your point is just that JavaFX is taking over from Swing for the limited areas in which Swing is used, I have no insight into that area."
    Now I don't really like attitudes when I get my question answered, but the high and mighty needs to stop. It clearly says Client-Server so I don't know why it's being denounced by this dude who thinks he obviously knows better.
    Anyways he talks about it only being able to connect to a DB, to which it says it uses EE tech such as EBJ, Restful, and Derby, so that's more than just DB right(I don't know since I havent' learned that yet)?
    It seems as if he's saying that only EE code can go up on a server? Or can SE code go up there as well?
    I'm looking to design a SaaS software with FX, so if this isnt' possible I would like to know possible other options(or just having all of the gui work on the client, and the rest on the backend)???
    Thanks!
    ~KZ
    Edited by: KonradZuse on Apr 30, 2013 11:26 AM

    This response is not a tutorial, I hope it gives you some verbiage to use in further searches.
    SaaS to me means that the service is running on the server. If you have the server and permission to run java apps there then you can use Java FX by having the server shuttle requests to the Java FX app. But this is probably not the intent of Saas (it would be more appropriate to use a java implemented web service).
    If you are using Netbeans then it is very easy to create demo projects; use "File/New Project" to run them on your local computer.
    Example File/New Project/Java Web/Web Application will give you a hello world web site very quickly. This will 1) start either tomcat or glassfish as the server. 2) launch an html page with "hello world". then you can use java script to talk with the server via ajax. Using this approach you are going to need to study JSP or J2EE stuff.
    After this is running you could start one of the Java Fx examples in Netbeans: File / New Project / Samples / WebViewBrowser. This will start a javaFX app that acts like a browser and runs on the client.
    So, start the "hello world" app in netbeans by right clicking it in the project pain and selecting "debug". Then start the webviewBrowser app the same way to load that web page that has "hello world" in it as all browsers do. In the WebviewBrowser (which is java fx) you can get at the javascript in the web page and do all kinds of stuff. You'll need to search for webviewBrowser examples.
    The above all assumes a Netbeans solution. But, as you probably know, there are no rules. The server can be in C++ and the client in C (or any other language). The server and client usally communicate via http or tcp. So you could have a server written in java (maybe J2ee or you can rewrite a http server from scratch which isn't that hard - search for "HttpServletRequest and HttpSession" ) and the client can be in Java FX (where the Java FX talks directly with the server via http (no javascript or web page in the middle) again there are probably hundreds of libraries to talk to a http server).
    I use HttpServletRequest and HttpSession on the server side with MySQL and xml. On the client I use javaScript but I am moving to a strictly Java FX solution. This will give me close to 100% java on both sides and for my purposes this will work. (I may need a little html in the middle for drag and drop installation.) I am hoping that work continues with porting Java FX to most devices: Android, IOS, WinPhone. It is already on Linux, Windows Desktops and Mac.
    Edited by: KevinPas on May 1, 2013 9:50 AM
    Edited by: KevinPas on May 1, 2013 9:56 AM

  • Problem to update Swing components from RMI object at server side

    Greetings, I have a RMI client/server application, both client and server have a Swing GUI. But at the server side, it appears to me that I can't pass object or make function call to my server GUI class. Because I can't have GUI instance or reference in my Remote object. (java.rmi.MarshalExceptio, java.io.NotSerializableException, blar blar ...)
    My problem is, if a client does something, I want to reflect the changes on the server side GUI. How can I do this except using a spin query?
    Any help would be greatly appreciated.
    Thanks.
    John
    Edited by: zgliang on Sep 13, 2007 3:30 AM

    I'd like to suggest you read the topic "Questions RMI & Swing & SwingWorker", which is similar to yours.

  • Client/Server Program with GUI

    Hello all...I've been working on an instant messenger type of program, and need a way to keep track of different clients using my server, and then posting that list to my clients' GUI, to show them who is "Online" Also, I am having trouble, letting my server know which client to send a message to...i.e. client1 tries to say "Hello" to client2 but nothing happens... Anyways I gonna keep pluggin away at it but if you have any insight let me know please...Damn I just got this new error a second ago, for no apperent reason...
    ReceivingThread.java [156:1] cannot resolve symbol
    symbol : constructor SendingThread (int)
    location: class SendingThread
    SendingThread sendingThread = new SendingThread(8205);
    ^
    1 error
    ...and here's the code for it, just popped up outta nowhere...thx again!!
    import java.io.*;
    import java.net.*;
    import java.util.StringTokenizer;
    public class ReceivingThread extends Thread {
    private byte[] message;
    private int portNumber;
    private InetAddress address;
    private BufferedReader input;
    private boolean keepListening = true;
    // ReceivingThread constructor
    public ReceivingThread( Socket clientSocket )
    // invoke superclass constructor to name Thread
    super( "ReceivingThread: " + clientSocket );
    // set timeout for reading from clientSocket and create
    // BufferedReader for reading incoming messages
    try {
    clientSocket.setSoTimeout( 5000 );
    input = new BufferedReader( new InputStreamReader(
    clientSocket.getInputStream() ) );
    // handle exception creating BufferedReader
    catch ( IOException ioException ) {
    ioException.printStackTrace();
    } // end ReceivingThread constructor
    // listen for new messages and deliver them to MessageListener
    public void run()
    String message;
    // listen for messages until stoppped
    while ( keepListening ) {
    // read message from BufferedReader
    try {
    message = input.readLine();
    // handle exception if read times out
    catch ( InterruptedIOException interruptedIOException ) {
    // continue to next iteration to keep listening
    continue;
    // handle exception reading message
    catch ( IOException ioException ) {
    ioException.printStackTrace();
    break;
    // ensure non-null message
    if ( message != null ) {
    // tokenize message to retrieve user name
    // and message body
    StringTokenizer tokenizer = new StringTokenizer( message, "|" );
    // ignore messages that do not contain a user
    // name and message body
    if ( tokenizer.countTokens() == 2 ) {
    // send message to the client through SendingThread; fill in proper info
    SendingThread sendingThread = new SendingThread(8205);
    sendingThread.start();
    else
    // if disconnect message received, stop listening
    if ( message.equalsIgnoreCase("DISCONNECT") ) {
    keepListening = false;
    } // end if
    } // end while
    // close BufferedReader (also closes Socket)
    try {
    input.close();
    // handle exception closing BufferedReader
    catch ( IOException ioException ) {
    ioException.printStackTrace();
    } // end method run
    }

    1) The error is down to the fact that you don't have a constructor declared for class SendingThread that accepts an int.
    2) To show who's on line use a static ArrayList at the server side. Everytime a user connects, just do:
    String user = "bob";
    arrayList.add(user);
    ArrayList is serialisable so you can serialise the object and send it over the network to the client. The client can deserialise the object and it will in effect have a copy of the object.
    When the client wants to display the names you just need to iterate over the array list.
    As new users connect you will have to update the list and also inform all other connected users that a new user has connected. You could do this by either pushing the data (client waits for data and server sends it immediately) or pulling the data at regular time intervals. I would suggest the first method as you will (or should) already have a thread set up to listen for incoming data.
    3) For sending messages between two hosts, you might want to set up a direct connection, however you would probably be better off sending message via the server. This makes setting up group chats much easier. Each message could be prefixed with the ID of the intended recipient. For group chat it will will be prefixed with group ID. The server should keep a record of group ID's to find out who's in each group.

  • Changes in server side java file not reflecting in Client side java code?

    Hi friends,
    iam using eclipse IDE, JBoss server, SWING GUI and Oracle DB
    ( looks like : SWINGGUI (Client) <--> EJB's (serverside) <---oracle )
    my problem is , when i make change in server side bean file, that changes are not reflecting in GUI programs.
    (for ex: iam adding settr and getter for a field and using that in GUI program. but its not identifying that setter or getter).
    please tell me what should i do for every change done to server side program, that should reflect / available to GUI?

    my problem is , when i make change in server side bean file, that changes are not reflecting in GUI programs.
    (for ex: iam adding settr and getter for a field and using that in GUI program. but its not identifying that setter or getter).what do you mean it's not "identifying" the methods?
    you have to call those methods you know
    are you getting NoSuchMethodError?
    please tell me what should i do for every change done to server side program, that should reflect / available to GUI?you haven't posted any code or error messages that might help us debug

  • Multiple Clients in Client/Server Program

    I'm currently trying to make a small Client/Server application that will mimic a very basic chat room program. The basic idea is that the Server side of the program is started and multiple Client programs can connect and communicate with each other. However, I'm having a few problems at the moment, mostly with figuring out how it can work.
    Firstly, I can communicate one to one with the server and the client as the client socket is stored in a variable. However, to make it possible to allow multiple connections I've used a thread for each new connection but I'm not sure how I can broadcast messages to every connection. Would it be safe enough to store each client socket in a list and then communicate that way? Not sure what will happen when the client disconnects though it seems to be an issue.
    I'm also not sure how every message can be broadcasted to every single connections to the server. The server program can send a message to every client but the clients message at the moment only goes to the server. Anyway here's a bit of my code so far:
    SwingWorker<Socket, Void> worker = new SwingWorker<Socket, Void>() {
            protected Socket doInBackground() throws Exception {
                // Client socket
                try {
                    while (!stopRequested) {
                        clientSocket = serverSocket.accept();
                        // Stop requested is checked twice because the accept() method
                        // waits for a connection
                        if (!stopRequested) {
                            HostFrame.getFeedbackTextArea().append("New Connection Found");
                            Thread clientThread = new HandlerThread(clientSocket);
                            clientThread.start();
                        else {
                            serverSocket.close();
                            clientSocket.close();
                catch (Exception e) {
                    HostFrame.getFeedbackTextArea().append("Failed to Connect with Client");
                    System.out.println(e.getMessage());
                return clientSocket;
        };The SwingWorker is used so that the GUI doesn't freeze when the server tries to find a connection. At the moment it just creates a thread for each new connection but I'm guessing this isn't what I'm going to be needing to handle more than one client. Also at the moment I have no way of directing a message to a specific socket I'm pretty much just using the standard method shown on the Sun website about Sockets. Any help would be much appreciated

    clientSocket = serverSocket.accept();'clientSocket' should be a local variable here.
    else {
    serverSocket.close();
    clientSocket.close();You shouldn't close 'clientSocket here'. All you're accomplishing is closing the most recently accepted client socket. What about the others? Generally speaking you should let the client-handling threads take care of their own sockets completely.
    return clientSocket;This return statement is meaningless. You may as well return null. SwingWorker doesn't care. Don't just return something because you've got it lying around. In this case you shouldn't have it lying around.
    At the moment it just creates a thread for each new connection but I'm guessing this isn't what I'm going to be needing to handle more than one client.That is exactly what you have to do to handle more than one client. Once you fix it as per above.
    Also at the moment I have no way of directing a message to a specific socket I'm pretty much just using the standard method shown on the Sun website about Sockets.You probably need to keep a Map of client sockets accepted, keyed by some client identifier.

  • Multithreading issue with Client/Server chat program

    In a nutshell, I just recently starting attempting to use Sockets and decided I wanted to give a go at a chat program. I have some experience with threads but I know little about how to find and fix multithreading issues. I think this is my problem right now since I am deadlocking while connecting and disconnecting client-side ... and updates about connection status of a client are not always displaying correctly server-side.
    [ Code Snippet|http://snipplr.com/view/15206/clientserver-chat-program/]
    Thanks for the help

    NOTE: all catch clauses have been omitted for clarity. They all just perform System.err.println() with the msg embedded
    Very valid point. I cut out the GUIs and just tried having the Server/Client communicate. I am still having concurrency issues. This is my first attempt at synchronized methods and locking objects so go easy on me if I did something(s) noob =D
    public class MySocket
        public static final String QUIT = "~~QUIT~~";
        private ObjectOutputStream out;
        private ObjectInputStream in;
        private Socket conn;
        public MySocket(String ip)
            obsList = new ArrayList<IClientObs>();
            try
                conn = new Socket(ip, 5000);
                if (conn.isConnected())
                    out = new ObjectOutputStream(conn.getOutputStream());
                    in = new ObjectInputStream(conn.getInputStream());
        public synchronized String nextMsg()
            String msg = "";
            try
                synchronized(in)
                    msg = (String)in.readObject();
                    notify(msg);
            return(msg);
        public synchronized boolean sendMsg(String msg)
            boolean sentMsg = false;
            try
                synchronized(out)
                    if (out != null)
                        out.writeObject(msg);
                        out.flush();
                        sentMsg = true;
            return(sentMsg);
        public synchronized void closeConn()
            try
                synchronized(this)
                    sendMsg(QUIT);
                    conn.close();
                    out.close();
                    in.close();
        public synchronized Socket getConn()
            return(conn);
        public synchronized ObjectOutputStream getOutStream()
            return(out);
        public synchronized ObjectInputStream getInStream()
            return(in);
       //Observer Pattern implemented below   
    public class Server extends Thread
        public static final int MAX_CLIENTS = 2;
        public static final String QUIT = "~~QUIT~~";
        private ServerSocket server;
        private ArrayList<ConnClient> conns;
        private int connCount;
         * Constructor for objects of class Server
        public Server()
            conns = new ArrayList<ConnClient>();
            obsList = new ArrayList<IServerObs>();
            connCount = 0;
        public void startNow()
            this.start();
        public void run()
            runServer();
        public synchronized void runServer()
            try
                setup();
                while (true)
                    waitForConn();
                    processComms();
        private synchronized void setup() throws IOException
            server = new ServerSocket(5000);
            notify("Server initialized.\n");
        private synchronized void waitForConn() throws IOException
            if (connCount < MAX_CLIENTS)
                notify("Waiting for connection...\n");
                Socket conn = server.accept();
                if (conn.isConnected())
                    conns.add(new ConnClient(conn));
                    notify("Client connected @ '" + conns.get(connCount).getIP() + "'.\n");
                    connCount++;
            else
                notify("Connection request rejected; max connections have been reached.\n");
        private synchronized void processComms() throws IOException, ClassNotFoundException
            //Receive any msgs sent by clients and forward msg to all clients
            for(ConnClient rcvClient : conns)
                String msg = rcvClient.nextMsg();
                //if client quit, then close connection and remove it from list
                if (msg.equals(QUIT))
                    notify("Client disconnected @ '" + rcvClient.getIP() + "'.\n");
                    rcvClient.closeConn();
                    conns.remove(rcvClient);
                    connCount--;
                else
                    for(ConnClient sndClient : conns)
                        sndClient.sendMsg(msg);
        public synchronized void shutdown()
            try
                server.close();
                for(ConnClient client :conns)
                    client.closeConn();
       //Observer Pattern implemented below
    }I also found another issue that I haven't thought up a way to deal with yet. When the user starts the program the follow line is executed "conn = server.accept();" which halts execution
    on that thread until a connection is established. What if the user wants to stop the server before a connection is made? The thread keeps running, waiting for a connection. How do I kill this thread?
    On this last issue (I figured by adding the follow code to my action listener inside of my server gui I could stop the thread safely but it's no good so far)
    public void actionPerformed(ActionEvent e)
            Object src = e.getSource();
            if (src == strBtn)
                if (server == null)
                    strBtn.setEnabled(false);
                    stpBtn.setEnabled(true);
                    server = new Server();
                    server.addObserver(this);
                    server.start();
                else
                    console.append("Console: Server is alread initiated.\n");
            else if (src == stpBtn)
                synchronized(server)
                strBtn.setEnabled(true);
                stpBtn.setEnabled(false);
                server.shutdown();
                server = null;
                console.append("Console: Server has been stopped.\n");
        }Edited by: mcox05 on May 21, 2009 10:05 AM
    Edited by: mcox05 on May 21, 2009 10:17 AM
    Edited by: mcox05 on May 21, 2009 10:58 AM
    Edited by: mcox05 on May 21, 2009 11:01 AM
    Edited by: mcox05 on May 21, 2009 11:03 AM
    Edited by: mcox05 on May 21, 2009 11:03 AM

  • How can i load file into database from client-side to server-side

    i want to upload file from client-side to server-side, i use the following code to load blob into database.
    if the file is in the server-side, it can work, but if it in the client-side, it said that the system cannot find the file. i think it only will search the file is in the server-side or not, it will not search the client-side.
    how can i solve it without upload the file to the server first, then load it into database??
    try
    ResultSet rset = null;
    PreparedStatement pstmt =
    conn.prepareStatement ("insert into docs values (? , EMPTY_BLOB())");
    pstmt.setInt (1, docId);
    pstmt.execute ();
    // Open the destination blob:
    pstmt.setInt (1, docId);
    rset = pstmt.executeQuery (
    "SELECT content FROM docs WHERE id = ? FOR UPDATE");
    BLOB dest_lob = null;
    if (rset.next()) {
    dest_lob = ((OracleResultSet)rset).getBLOB (1);
    // Declare a file handler for the input file
    File binaryFile = new File (fileName);
    FileInputStream istream = new FileInputStream (binaryFile);
    // Create an OutputStram object to write the BLOB as a stream
    OutputStream ostream = dest_lob.getBinaryOutputStream();
    // Create a tempory buffer
    byte[] buffer = new byte[1024];
    int length = 0;
    // Use the read() method to read the file to the byte
    // array buffer, then use the write() method to write it to
    // the BLOB.
    while ((length = istream.read(buffer)) != -1)
    ostream.write(buffer, 0, length);
    pstmt.close();
    // Close all streams and file handles:
    istream.close();
    ostream.flush();
    ostream.close();
    //dest_lob.close();
    // Commit the transaction:
    conn.commit();
    conn.close();
    } catch (SQLException e) {

    Hi,
    Without some more details of the configuration, its difficult to know
    what's happening here. For example, what do you mean by client side
    and server side, and where are you running the upload Java application?
    If you always run the application on the database server system, but can't
    open the file on a different machine, then it sounds like a file protection
    problem that isn't really connected with the database at all. That is to
    say, if the new FileInputStream (binaryFile) statement fails, then its not
    really a database problem, but a file protection issue. On the other hand,
    I can't explain what's happening if you run the program on the same machine
    as the document file (client machine), but you can't write the data to the
    server, assuming the JDBC connection string is set correctly to connect to
    the appropriate database server.
    If you can provide some more information, we'll try to help.
    Simon
    null

  • RUN SERVER SIDE OS COMMAND OR ANY EXECUTABLE FILE FROM CLIENT

    Would you provide a complete example regarding execution Server side OS command or program from ORACLE SQL CLIENT OR FORM. This client may be a remote client.

    instead of just copying jvm.dll, I would recommend installing Java through the installer as there are most likely other files that jvm.dll is dependent on, etc.
    It's been a while since I have worked with HAL integrations (Vignette), but I believe you will need HFM client installed on the end user machine.
    If you have a lot of machines, this could be a bit annoying. Because of that when we used HAL, we made a custom web front-end that ran on a server with the HAL programs. It was more work to build the web U/I; however, from a management perspective, it was a lot easier to control/maintain.
    $.02

Maybe you are looking for

  • Transferring an ebook to Samsung Galaxy tablet

    I looked at Adobe's list of supported ebook devices/apps for use with Digital Editions and found that Mantano Reader--currently installed on my Galaxy Note 4--was on the list. I then followed the directions to connect the tablet to the computer on wh

  • T530 multiple display in dock, single without dock

    Hi I have a problem with dispplay settings on my T530 with nvidia 5400m. If i Boot the computer in the docking with lid closed I get two displays (fine!). If I boot the computer with lid open in dock i get all black screens (three) but i can move the

  • About decimal point

    hi,expert! in the cube ,i find the data is 0.5,but it display as 1.0 in my query,who can help me ? thanks!

  • Do you ship to egypt ?

    do you ship macbook pro to egypt ? and what about warranty ? is it available in egypt ?

  • Where do I find my way of SAP

    Hello to all I'm Computer Programmer. My experience in programming, databases, and virtualization technologies Good experience and I want to learn SAP .. Where do I find my way of SAP and advantages and difficulties and differences