Client/Server API with push?

I set up a simple Socket client server architecture with the Java socket API. However, my clients sometimes are initiators or requests, and sometimes my server is the initiator of infos. Example: client want to get infos from server but also want to tell the server something. The server tells all registered clients something but also can accept requests from clients. So both sides are client AND server (depending on what they currently want to do).
The socket API is just a classic client/server API, i.e. a server listens and a client sends requets and get responses. For my server to send requests to all clients, this is not enough. Is the only way to have all clients offering a socket server on their computer, too? so that this 2-way-request-communication works?
This is basically some kind of "push" technology, but i don't want my clients to "poll" the server just to emulate the feature of sending requests from the server to the client. Is there some other (perhaps non-socket) API that offers this?

@sjasja: how is the socket api symmetrical?It is, trust me! Connection initiation isn't, but after that it is. (Let's assume connected TCP/IP.)
The server does bind() and accept(), the client does connect(). After that, the connection is symmetrical: either end can issue any number of read() and write() calls in any order. You write() to a socket, it pops out from read() at the other end (though not necessarily as a single packet; TCP/IP is stream oriented, so write() "packets" can and will be glued together, or fragmented at the whimsy of network routers and friends.)
- accept() //wait for client to send request
- socket.getInputStream() //read request
- socket .getOutputStream() //write responseThose don't read or write; they get streams which you can read from and write to.
In the server, when accept() returns a new connection, you'd start a reader thread for that client. The thread would read() (or readLine() if you implement a line-oriented protocol) and handle the incoming messages. Whenever you want to write to the client, write to the stream returned by socket.getOutputStream(). You may need to synchronize writes if you have several threads that do sequences of write()s that need to arrive at the client sequentially.
As to the difficulty of socket programming: I don't think it particularly difficult. But then I've written dozens of socket programs since my first one in '85... The Java Tutorial socket chapter shows a simple client/server pair; not terribly difficult I think. In particular, check out the KKMultiServer at the bottom of the sample server chapter.

Similar Messages

  • Client Server Application with images or icons

    I made a Client Server application with JFrames, but I put a jLabel with an icon, and I can't run the Client.
    It says java.lang.NullPointerException
    Do you know why I can't see the icon in the JLabel? It isn't an applet, it's an application with JFrames.

    You have to explain the problem better if you want some help. Also show the code which is giving you the nullpointerexception(Do not forget codetags!).

  • White Paper: End-to-End Client/Server Security with the Adobe Flash Platform

    Today we released a sorely needed white paper on end-to-end client/server security with the Adobe Flash Platform.  This information is directly applicable to the Adobe  LiveCycle family as well as Flash RIAs. 
    http://www.slinnbooks.com/books/enterprise/securityWhitePaper.shtml
    Thank you,
    Mike
    Michael Slinn
    http://micronauticsresearch.com
    http://slinnbooks.com

    Hai,
           Delete the certificate in the ABAP system and try importing the new certificate from the EP instance(ADS) and export into the ABAP and check...
    Thanks and Regards,

  • Client server code with errors could some one please help me!!!

    I am using a random access file to design the two interfaces for my client and my server is this the right thing to do? Oh could some one give me some example code of client server interfaces.
    I got an error in the code for the interfaces and I don't know what it is could some one please help me!!
    Heres the error in the code: This is for RegisterCustomer
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    class RegisterCustomer extends JPanel implements ActionListener
    // Button for registering a customer
    private JButton jbtRegister;
    // Customer information panel
    private CustomerPanel customerPanel; (The error is on this line and it says Field type customer panel is missing)
    // Random access file
    private RandomAccessFile raf;
    Second error: Its in the ViewCustomer:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    // View customer panel
    class ViewCustomer extends JPanel implements ActionListener
    // Buttons for viewing customer information
    private JButton jbtFirst, jbtNext, jbtPrevious, jbtLast;
    // Random access file
    private RandomAccessFile raf = null;
    // Current customer record
    private Customer customer = new Customer();
    // Create a customer panel
    private CustomerPanel customerPanel = new customerPanel(); (its on this line and it says field type CustomerPanel is missing)
    // File pointer in the random access file
    private long lastPos;
    private long currentPos;
    Heres the code for the customerPanel:
    // Customer Panel.java: Panel for displaying Customer information
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    public class customerPanel extends JPanel
         JTextField jtfRegistrationnumber = new JTextField(30);
         JTextField jtfSeatingcapacity = new JTextField(20);
    JTextField jtfStartdateofhire = new JTextField(20);
    JTextField jtfDurationofhire = new JTextField(10);
    JTextField jtfManufacture = new JTextField(20);
    JTextField jtfModel = new JTextField(15);
         JTextField jtfEnginesize = new JTextField(15);
    JTextField jtfCharge = new JTextField(20);
    JTextField jtfMileage = new JTextField(10);
    // Constuct a customer panel
    public customerPanel()
    // Set the panel with line border
    setBorder(new BevelBorder(BevelBorder.RAISED));
    // Panel p1 for holding all the labels
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(3, 1));
    p1.add(new JLabel("Registration number"));
    p1.add(new JLabel("Seating capacity"));
    p1.add(new JLabel("Start date of hire"));
    p1.add(new JLabel("Duration of hire"));
    p1.add(new JLabel("Manufacture"));
    p1.add(new JLabel("Model"));
    p1.add(new JLabel("Engine size"));
    p1.add(new JLabel("Charge"));
    p1.add(new JLabel("Mileage"));
    // Panel jpRegistration number for registration number
    JPanel jpRegistrationnumber = new JPanel();
    jpRegistrationnumber.setLayout(new BorderLayout());
    jpRegistrationnumber.add(new JLabel("Registration number"), BorderLayout.WEST);
    jpRegistrationnumber.add(jtfRegistrationnumber, BorderLayout.CENTER);
    // Panel jpSeating capacity for holding Seating capacity
    JPanel jpSeatingcapacity = new JPanel();
    jpSeatingcapacity.setLayout(new BorderLayout());
    jpSeatingcapacity.add(new JLabel("Seating capacity"), BorderLayout.WEST);
    jpSeatingcapacity.add(jtfSeatingcapacity, BorderLayout.CENTER);
         // Panel jpStart date of hire for holding start date of hire
    JPanel jpStartdateofhire = new JPanel();
    jpStartdateofhire.setLayout(new BorderLayout());
    jpStartdateofhire.add(new JLabel("Start date of hire"), BorderLayout.WEST);
    jpStartdateofhire.add(jtfStartdateofhire, BorderLayout.CENTER);
    // Panel jpDuration of hire for holding Duration of hire
    JPanel jpDurationofhire = new JPanel();
    jpDurationofhire.setLayout(new BorderLayout());
    jpDurationofhire.add(new JLabel("Duration of hire"), BorderLayout.WEST);
    jpDurationofhire.add(jtfDurationofhire, BorderLayout.CENTER);
    // Panel p2 for holding jpRegistration number and jpSeating capacity and start date of hire and duration of hire
    JPanel p2 = new JPanel();
    p2.setLayout(new BorderLayout());
    p2.add(jpRegistrationnumber, BorderLayout.WEST);
    p2.add(jpSeatingcapacity, BorderLayout.CENTER);
    p2.add(jpStartdateofhire, BorderLayout.CENTER);
    p2.add(jpDurationofhire, BorderLayout.CENTER);
    // Panel p3 for holding jtfManufacture and p2
    JPanel p3 = new JPanel();
    p3.setLayout(new BorderLayout());
    p3.add(jtfManufacture, BorderLayout.CENTER);
    p3.add(p2, BorderLayout.EAST);
    // Panel p4 for holding jtfModel, jtfEngine size, charge and mileage and p3
    JPanel p4 = new JPanel();
    p4.setLayout(new GridLayout(3, 1));
    p4.add(jtfModel);
    p4.add(jtfEnginesize);
    p4.add(jtfCharge);
    p4.add(jtfMileage);
    p4.add(p3);
    // Place p1 and p4 into customerPanel
    setLayout(new BorderLayout());
    add(p1, BorderLayout.WEST);
    add(p4, BorderLayout.CENTER);
    // Get customer information from the text fields
    public Customer getCustomer()
    return new Customer(jtfRegistrationnumber.getText().trim(),
                             jtfSeatingcapacity.getText().trim(),
                                  jtfStartdateofhire.getText().trim(),
                             jtfDurationofhire.getText().trim(),
                             jtfManufacture.getText().trim(),
                             jtfModel.getText().trim(),
                                  jtfEnginesize.getText().trim(),
                             jtfCharge.getText().trim(),
                             jtfMileage.getText().trim());
    // Set customer information on the text fields
    public void setCustomer(Customer s)
    jtfRegistrationnumber.setText(s.getRegistrationnumber());
    jtfSeatingcapacity.setText(s.getSeatingcapacity());
    jtfStartdateofhire.setText(s.getStartdateofhire());
    jtfDurationofhire.setText(s.getDurationofhire());
    jtfManufacture.setText(s.getManufacture());
    jtfModel.setText(s.getModel());
    jtfEnginesize.setText(s.getEnginesize());
    jtfCharge.setText(s.getCharge());
    jtfMileage.setText(s.getMileage());
    Could someone please help me and tell me what these two errors mean and how I could get rid of them

    Can some one take a look at this code and tell me how to get all my jlabels to line up alone side their jtf.
    Because it looks like this the picture in the attached file and this is the code for it:
    public customerPanel()
    // Set the panel with line border
    setBorder(new BevelBorder(BevelBorder.RAISED));
    // Panel p1 for holding labels Name, Street, and City
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(5, 1));
    p1.add(new JLabel("Registration Number:"));
    p1.add(new JLabel("Seating Capacity:"));
    p1.add(new JLabel("Engine Size:"));
    p1.add(new JLabel("Start date of hire"));
    p1.add(new JLabel("Duration of hire"));
    JPanel p2 = new JPanel();
    p2.setLayout(new GridLayout(5, 1));
    p2.add(jtfRegistrationnumber);
    p2.add(jtfSeatingcapacity);
    p2.add(jtfEnginesize);
    p2.add(jtfStartdateofhire);
    p2.add(jtfDurationofhire);
    //JPanel p3 = new JPanel();
    //p3.add(p1, BorderLayout.WEST);
    //p3.add(p2, BorderLayout.NORTH);
    JPanel p4 = new JPanel();
    p4.setLayout(new GridLayout(4, 1));
    p4.add(new JLabel("Manufacture:"));
    p4.add(new JLabel("Model:"));
    p4.add(new JLabel("Mileage:"));
    p4.add(new JLabel("Charge:"));
    JPanel p5 = new JPanel();
    p5.setLayout(new GridLayout(4, 1));
    p5.add(jtfManufacture);
    p5.add(jtfModel);
    p5.add(jtfMileage);
    p5.add(jtfCharge);
    // JPanel p6 = new JPanel();
    // p6.setLayout(new BorderLayout());
    // p6.add(p4, BorderLayout.SOUTH);
    // p6.add(p5, BorderLayout.EAST);
    // Place p1 and p4 into CustomerPanel
    setLayout(new BorderLayout());
    add(p1, BorderLayout.WEST);
    add(p2, BorderLayout.NORTH);
    add(p4, BorderLayout.SOUTH);
    add(p5, BorderLayout.EAST);
    So could someone please help me and correct my code so that each text lable is lined up next to its jtf java text field.

  • Client == server - problems with callbacks

    Hi everyone!
    I'm having trouble establishing bidirectional communication between a client and a server (code samples are below).
    Both classes (client & server) extend UnicastRemoteObject and implement Interfaces that are extending Remote. Now the client looks up the server and tries to register itself at the server by calling a method like this:
    remote_server.setClient(this);
    as long as I execute both programs in the same LAN this method-call works fine, but when client and server connect through internet I'm getting the following exception:
    ---------------------- Exception ------------------------>
    java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
         java.rmi.ConnectException: Connection refused to host: 192.168.0.3; nested exception is:
         java.net.ConnectException: Connection timed out
         at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:292)
    <---------------------- Exception ------------------------
    maybe helpful:
    - 192.168.0.3 is the client's LAN-IP
    - I am directly connected to the internet via ADSL-modem (no router)
    I searched the forums for several hours now, I read through the following tutorial,
    http://developer.java.sun.com/developer/onlineTraining/rmi/exercises/RMICallback/index.html
    but still I didn't find a solution.
    I already spent a lot of time developing this and I start to get desperate, so I hope someone of you out there can help me!
    pilord
    ==================== Codesamples =======================>
    public class ServerImpl extends UnicastRemoteObject implements Server {
    Client client;
    public ServerImpl() {
    LocateRegistry.getRegistry(1096).rebind("test",this);
    /* specified in Remote-Interface: Server*/
    public void setClient(Client client) {
    this.client = client;
    public class ClientImpl extends UnicastRemoteObject implements Client {
    public ClientImpl() {
    Server s = Naming.lookup("rmi://***.***.***.***:1096/test");
    s.setClient(this); // HERE is the trouble.
    <==================== Codesamples =======================

    Don't feel lost, crumb. Http tunnelling is not as complex as it seems. I just started using RMI at my new job here and in a couple of weeks I've already picked up on alot of what I needed to know. (I just posted a question myself on the same topic.) Basically what you have to do is set up a web server for RMI to talk to at the server side. It will work if the webserver is listening on port 80 with the rmiservlet.ServletHandler registered to respond to any path request of cgi-bin/java-rmi.cgi. In other words "cgi-bin/java-rmi.cgi" should be the servlet-mapping of the ServletHandler. The servlet merly acts as a proxy on behalf of the RMI client and fowards the request to the desired port on the server. If you know how to set up a servlet as the default web app then it is really a breeze. On the client side you only need to set the http.proxyHost and http.proxyPort system properties to the appropriate values for your proxy server. (I mistyped these property names in my prior post use what I have here as I just read it out of the RMI book.) Do a search on HTTP tunnelling and you should turn up dozens of hits. I have the source to the servlet if you need it. I've already modified it for my own purposes though it should still work for you. If you forego http tunnelling then you'll have to do a complete app rewrite to use another protocol because RMI just doesn't work through firewalls without it. Alternatively you can get down and dirty with some low level sockets coding (this is what I'm thinking I'll end up doing eventually) to get it working without standard RMI/HTTP but that's way more complex. Unfortunately it looks like your callback code will need to be rewritten unless you either go commercial or do the socket stuff. (There does seem to be a shareware product called rmi doves that would help you here.) I'll be happy to assits you in any way as you need help.
    Cliff

  • Client Server Socket With GUI

    Hi,
    As the name of the forum suggests I am very new to this whole thing.
    I am trying to write a client/server socket program that can encrypt and decrypt and has a GUI, can't use JCE or SSL or any built in encryption tools.
    I have the code for everything cept the encryption part.
    Any help, greatly appreciated,

    tnks a million but how do i incorporate that into the following client and server code:
    here's the client code:
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketClient extends JFrame
              implements ActionListener {
    JLabel text, clicked;
    JButton button;
    JPanel panel;
    JTextField textField;
    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    SocketClient(){ //Begin Constructor
    text = new JLabel("Text to send over socket:");
    textField = new JTextField(20);
    button = new JButton("Click Me");
    button.addActionListener(this);
    panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.setBackground(Color.white);
    getContentPane().add(panel);
    panel.add("North", text);
    panel.add("Center", textField);
    panel.add("South", button);
    } //End Constructor
    public void actionPerformed(ActionEvent event){
    Object source = event.getSource();
    if(source == button){
    //Send data over socket
    String text = textField.getText();
    out.println(text);
         textField.setText(new String(""));
    //Receive text from server
    try{
         String line = in.readLine();
    System.out.println("Text received :" + line);
    } catch (IOException e){
         System.out.println("Read failed");
         System.exit(1);
    public void listenSocket(){
    //Create socket connection
    try{
    socket = new Socket("HUGHESAN", 4444);
    out = new PrintWriter(socket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (UnknownHostException e) {
    System.out.println("Unknown host: HUGHESAN.eng");
    System.exit(1);
    } catch (IOException e) {
    System.out.println("No I/O");
    System.exit(1);
    public static void main(String[] args){
    SocketClient frame = new SocketClient();
         frame.setTitle("Client Program");
    WindowListener l = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.addWindowListener(l);
    frame.pack();
    frame.setVisible(true);
         frame.listenSocket();
    SERVER Code
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketServer extends JFrame
              implements ActionListener {
    JButton button;
    JLabel label = new JLabel("Text received over socket:");
    JPanel panel;
    JTextArea textArea = new JTextArea();
    ServerSocket server = null;
    Socket client = null;
    BufferedReader in = null;
    PrintWriter out = null;
    String line;
    SocketServer(){ //Begin Constructor
    button = new JButton("Click Me");
    button.addActionListener(this);
    panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.setBackground(Color.white);
    getContentPane().add(panel);
    panel.add("North", label);
    panel.add("Center", textArea);
    panel.add("South", button);
    } //End Constructor
    public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    if(source == button){
    textArea.setText(line);
    public void listenSocket(){
    try{
    server = new ServerSocket(4444);
    } catch (IOException e) {
    System.out.println("Could not listen on port 4444");
    System.exit(-1);
    try{
    client = server.accept();
    } catch (IOException e) {
    System.out.println("Accept failed: 4444");
    System.exit(-1);
    try{
    in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    out = new PrintWriter(client.getOutputStream(), true);
    } catch (IOException e) {
    System.out.println("Accept failed: 4444");
    System.exit(-1);
    while(true){
    try{
    line = in.readLine();
    //Send data back to client
    out.println(line);
    } catch (IOException e) {
    System.out.println("Read failed");
    System.exit(-1);
    protected void finalize(){
    //Clean up
    try{
    in.close();
    out.close();
    server.close();
    } catch (IOException e) {
    System.out.println("Could not close.");
    System.exit(-1);
    public static void main(String[] args){
    SocketServer frame = new SocketServer();
         frame.setTitle("Server Program");
    WindowListener l = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.addWindowListener(l);
    frame.pack();
    frame.setVisible(true);
         frame.listenSocket();
    Again help on this is very welcomed

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

  • Making a Client & Server app with UDP

    Hello fellahs, as the title of this post says I'm making a client and server application. The server are supposed to handel several clients, and the communication is done true UDP.
    I have got two questions concerning this. The first one is if a exception is throws in the server should I then send the exception back to the client in serialized form. If I choose to do this then I also would need to handel the exception classen to the client. Or should I send back a regular IOException and use it's init cause to define the exception which occured in the server.
    The second question is concerning the multi client support. If this is going to work then I would need to time-out the connection i the server environment, and I have not a clue about how long it should be?
    /thanks in regards Ali.

    superdeportivo wrote:
    Hello fellahs, as the title of this post says I'm making a client and server application. The server are supposed to handel several clients, and the communication is done true UDP. Out of interest why have you chosen UDP rather than TCP?
    I have got two questions concerning this. The first one is if a exception is throws in the server should I then send the exception back to the client in serialized form. If I choose to do this then I also would need to handel the exception classen to the client. Or should I send back a regular IOException and use it's init cause to define the exception which occured in the server. That is up to you, you can do either. I would do the first option.
    The second question is concerning the multi client support. If this is going to work then I would need to time-out the connection i the server environment, and I have not a clue about how long it should be?It should be long enough that you don't timeout a valid connection. There is no simple answer to this.

  • OSX: multi client server app with NSNetService

    hello
    i have a small osx server app
    that uses NSNetService to manage connection and set up streams
    but it seems to stop advertising as soon as a clients connects
    how can i make it multiclient so it keeps advertising and when a new client connects uses the same streams ?
    thanks in advance
    nonnus

    superdeportivo wrote:
    Hello fellahs, as the title of this post says I'm making a client and server application. The server are supposed to handel several clients, and the communication is done true UDP. Out of interest why have you chosen UDP rather than TCP?
    I have got two questions concerning this. The first one is if a exception is throws in the server should I then send the exception back to the client in serialized form. If I choose to do this then I also would need to handel the exception classen to the client. Or should I send back a regular IOException and use it's init cause to define the exception which occured in the server. That is up to you, you can do either. I would do the first option.
    The second question is concerning the multi client support. If this is going to work then I would need to time-out the connection i the server environment, and I have not a clue about how long it should be?It should be long enough that you don't timeout a valid connection. There is no simple answer to this.

  • Client-Server programming with Sockets

    How to read user input from GUI in client socket and send the data to server socket? Can someone give example of the coding?
    Thank you.

    Take a look at reply 28 of Program hanging on a Thread. That post is a swing based socket client. If you are using Swing you must ensure that all swing activity occurs on the AWT Event Dispatch Thread. That's the reason for the use of invokeLater.
    Reply 21 on the same thread is a multithreaded command line server.

  • Framework for client-server Architecture in Java !!!! With swing

    Hi,
    Considering the scenario where we are having the Client-Server application and the rich clients at the client place , based on the frames.I have though of the logic as :
    Client -----------> ClientComponentframeWorkObject(Genric Objects) ---------> reading the data from the configurable files to find where to take the user action ---------> will call the Servercomponetobject(Generic objects) can be Servlet or just a object which connects to the server(DB).I have been able to find the open-source frame work at the Apache ,all covering the server-side framework so i though of doing some work with the framework covering the client(swing) -server Archetect.Even I dont know how the existing server side framework support the swing client.
    I would appericiate if someone who had worked on the client server requirement with java , could share the knowledge about the framework being used in the existing work.
    regards
    Vicky

    Hi,
    GENERIC CLIENT COMPONENT:
    package com.nst.clientcomp;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public abstract class ClientComp extends JFrame
      protected JFrame currentframe;     
      protected JPanel  panel;
      public ClientComp()
           // To decide if the ClientComp to be Frame or the Panel.
        //panel=this;     
        //currentframe=new JFrame();
        panel=new JPanel();     
        currentframe=this;
      // Just Concentrate on the GUI , look and feel here .......And the user action will generate
      // generate the event which should call the callNextView()..The component developer have to
      // concentrate on the writing the display() and the callNextView()..
      public abstract void display() ;
      // This is the Final action.Template Pattern being Called
      public String action()
           readServerObj();
           processContent();
           display();              
           return null;
       Reading of the value object which is being Passes from the Server.As per the Design it is
       called VOFS and will be read here.Here
       1) Connect to the Server
       2) Pass the VOFC through the socket connection
       3) Also obtain the VOFS(Value object from server) 
       In certain application it can be implemented here
      public Object readServerObj()
            System.out.println("Hello from ServerObj!!! Should be implemented ");
            return null;
       Processing the Sever Value Object, which is basically as VOFS.It is processed by the
       Client.And infact the Value object from Client(VOFC) should be generated here for next
       user interaction from the Client.
      public void processContent()
            System.out.println("Hello from processContent !!! Should be implemented ");
      // Clear the Frame
      private void cleanUp()
         currentframe.dispose();
         Contains the place where next view takes.Before this is invoked the cache copy of the
         StateObject should be stored in the appropriate Data Structure......      
      public void callNextView(ClientComp com)                     
            panel.removeAll();
            com.action();
            cleanUp();
    }   COMONENTS AS PER THE FRAMEWORK :
    package com.nst.clientcomp;
    import javax.swing.*;
    import java.awt.event.*;
    public class Comp1 extends ClientComp implements ActionListener
      JTextField t,t1;     
    //Default display , displaying the screen.This should be the abstract method
      public void display()
        JLabel l=new JLabel("UserName");
        t=new JTextField(10);
        JLabel l1=new JLabel("Password");
        t1=new JPasswordField(10);
        t.setText("admin");
        t1.setText("admin");
        JButton b=new JButton("Login");
        b.addActionListener(this);
           panel.add(l);
           panel.add(t);
           panel.add(l1);
           panel.add(t1);
           panel.add(b);
           currentframe.getContentPane().add(panel);
           currentframe.setSize(400,400);
           currentframe.setVisible(true);      
      public static void main(String ar[]) throws Exception     
           ClientComp c1 = (ClientComp)(Class.forName(ar[0])).newInstance();
           c1.action();             
           System.out.println("Hello11");
      public void actionPerformed(ActionEvent e)
           //Do someprocessing if required
           if(t.getText().equals("admin")&&t1.getText().equals("admin"))
           callNextView(new Comp2());  
           else
            System.out.println("invalid login");     
    } Similarly you can develop the other components and you have to take care of the display() and the user action Event which eventually calls the callNextView.I hope there might be the cases where this has been implemented ..
    Regards
    Vicky

  • Want client to communicate with server

    I am making a client/server application with the client being an applet and the server a program. The program is for a fictional chinese restaurant where the user selected a dish (using four radio buttons) and depending on the radio button selected, four ingrediants show as check boxes(their value also changes depending on the radio button selected).
    I want the client to inform the server which radio button and check boxes have been selected so that the server can return the different ingrediants and their values in addition to working out the total price for the ingrediants selected. The problem is, I am unsure as to how to achieve this. Here is my code, I know it has problems, but i think it is generally OK:
    client code:
    import java.io.*;
    import java.net.*;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class AppletClientClass extends Applet implements
    ActionListener {
         radPanel = new Panel();
         chePanel = new Panel();
         radio = new CheckboxGroup();
         radioOne = new Checkbox("Set Dinner A", false, radio);
         radPanel.add(radioOne);
         radioOne.addItemListener(this);
         radioTwo = new Checkbox("Set Dinner B", false, radio);
         radPanel.add(radioTwo);
         radioTwo.addItemListener(this);
         radioThree = new Checkbox("Set Dinner C", false, radio);
         radPanel.add(radioThree);
         radioThree.addItemListener(this);
         radioFour = new Checkbox("Set Dinner D", false, radio);
         radPanel.add(radioFour);
         radioFour.addItemListener(this);
         checkOne = new Checkbox(" ");
         chePanel.add(checkOne);
         checkOne.addItemListener(this);
         checkTwo = new Checkbox("ingre. 2");
         chePanel.add(checkTwo);
         checkTwo.addItemListener(this);
         checkThree = new Checkbox("ingre. 2");
         chePanel.add(checkThree);
         checkThree.addItemListener(this);
         checkFour = new Checkbox("ingre. 2");
         chePanel.add(checkFour);
         checkFour.addItemListener(this);
         checkFive = new Checkbox("ingre. 2");
         chePanel.add(checkFive);
         checkFive.addItemListener(this);
         txtField = new TextField (40);
         add(txtField);
         add(radPanel);
         add(chePanel);
         public void actionPerformed (ActionEvent ev) {
         try
    Socket cts = new
    Socket(getCodeBase().getHost(), 6000);
         DataInputStream isfs = new
    DataInputStream(cts.getInputStream());
         DataOutputStream osts = new
    DataOutputStream(cts.getOutputStream());
              osts.writeDouble(Double.parseDouble(unknown));//want this line to tell the server which buttons have been selected
         osts.flush();
         double input = isfs.readDouble(sum);
              txtField.setText("�" + String.valueOf(sum));
    } catch (IOException ex) {
                   System.out.println(ex);
    Server code:
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    public class AppletServerClass {
         public static void main(String[] args) {
              try
                   ServerSocket ss = new ServerSocket(6000);
                   Socket ctc = ss.accept(); // ctc = connect to client
                   DataInputStream isfc = new DataInputStream(ctc.getInputStream()); // isfc = input stream from client
                   DataOutputStream ostc = new DataOutputStream(ctc.getOutputStream()); // output stream to client
                   double input = isfc.readDouble();
              double sum = 0;
              double ingre1 = 0;
              double ingre2 = 0;
              double ingre3 = 0;
              double ingre4 = 0;
              double ingre5 = 0;
              double totalIngre1 = 0;
              double totalIngre2 = 0;
              double totalIngre3 = 0;
              double totalIngre4 = 0;
              double totalIngre5 = 0;
              if(radioOne.getState() == true) // prices and ingredients if radio button one is selected
                   ingre1 = 3.5;
                   ingre2 = 6;
                   ingre3 = 9;
                   ingre4 = 12;
                   ingre5 = 7;
                   checkOne.setLabel("CurrySauce");
                   checkTwo.setLabel("Egg Fried Rice");
                   checkThree.setLabel("Chicken Chow Mein");
                   checkFour.setLabel("Prawn Crackers");
                   checkFive.setLabel("Meatballs");
              if (radioTwo.getState() == true) // prices and ingredients if radio button two is selected
                   ingre1 = 5;
                   ingre2 = 4;
                   ingre3 = 7;
                   ingre4 = 8;
                   ingre5 = 2;
                   checkOne.setLabel("Chips");
                   checkTwo.setLabel("Egg Fried Rice");
                   checkThree.setLabel("Chicken Chop Suey");
                   checkFour.setLabel("Fried Duck");
                   checkFive.setLabel("Omelette");
              if (radioThree.getState() == true)// prices and ingredients if radio button three is selected
                   ingre1 = 4;
                   ingre2 = 5;
                   ingre3 = 8;
                   ingre4 = 9;
                   ingre5 = 8;
                   checkOne.setLabel("Chicken");
                   checkTwo.setLabel("Curry");
                   checkThree.setLabel("Cod");
                   checkFour.setLabel("Noodles");
                   checkFive.setLabel("Meatballs");
              if (radioFour.getState() == true)// prices and ingredients if radio button four is selected
                   ingre1 = 4;
                   ingre2 = 3;
                   ingre3 = 6;
                   ingre4 = 2;
                   ingre5 = 4;
                   checkOne.setLabel("Roast Duck");
                   checkTwo.setLabel("Noodles");
                   checkThree.setLabel("Fried Squid");
                   checkFour.setLabel("Soup");
                   checkFive.setLabel("Fish");
              if (checkOne.getState() == true)
                   totalIngre1 = ingre1;
              if (checkTwo.getState() == true)
                   totalIngre2 = ingre2;
              if (checkThree.getState() == true)
                   totalIngre3 = ingre3;
              if (checkFour.getState() == true)
                   totalIngre4 = ingre4;
              if (checkFive.getState() == true)
                   totalIngre5 = ingre5;
                   sum = totalIngre1 + totalIngre2 + totalIngre3 + totalIngre4 + totalIngre5;
                   ostc.writeDouble(sum);
                   ostc.flush();
                   System.out.println("The total price for this meal is " + sum);
              } catch (IOException e) {
                   System.out.println(e);

    I've not looked over your code extrememly closely, but it looks like you might be mixing client and server responsibilities. In your client you need to have all the code that deals with the UI. There shouldn't be any mention of labels or check boxes in the server code. You might want the flow to be:
    Client:
    Presents a series of radio buttons for meal possibilities
    Queries the server for a list of ingredients for a selected meal
    Displays a meal-sensitive list of ingredients
    Submits the order to the server
    Server
    Accepts a request for a meal ingredient list
    Responds with the ingredient list
    Accepts an order
    responds with a total
    Then you need to work out how the client sends the meal possibility to the server, your current scheme of a double works, but it's easier (IMO) to use a String as a generic parameter type to move things back and forth with - that way you are always dealing with Strings. And you need to work out how the server sends an ingredient list to the client - you could use a delimited String and tokenize it. And then you need to work out how the client submits a finished order to the server, maybe a String that says "ORDER_COMPLETE" or something, with a delimited list of ingredients and the meal key.
    I hope that made sense, and good luck
    Lee

  • Oracle Forms 6i client/server against an Oracle 10gR2 database

    Hello
    We have the following situation:
    Oracle Forms6i/Reports6i client server application against an Oracle 8i cost-based database. we want to migrate this application
    step 1:
    Migrate the database to 10gr2, but do not touch the client application
    Go live
    step 2:
    Migrate the development environment to 6i webforms.
    Production environment stays client server.
    With this construction we can still create new patches/functionality.
    step 3:
    Migrate to Forms10gR2 (and reports)
    I know Forms 6i is not supported anymore.
    My question is on step 1.
    When I read NOTE: 338513.1 entitled "Is Forms/Reports 6i Certified To Work Against Oracle Server 10g Rel 1, Rel 2 or 11g?" carefully
    it says that Forms 6i is not certified against 10gR2.
    On OTN I read several posts that this works ok (assuming you do not use the wrong character set).
    I also read on OTN that patch 18 (which is only supported for EBS customers) is certified against 10gR2.
    The questions:
    - Is Oracle Forms patch 18 certified against an Oracle 10gR2 database? (or only for EBS)
    - Is there anybody out there that can confirm that Oracle Forms 6i C/S works against Oracle 10gR2
    Regards Erik

    Thank you.
    Now I found it.
    But how do I read that page.
    It says:
    Client Certifications
    OS      Product      Server Status
    XP      6.0.8.27.0 Patch 18      N/A      Desupported
    Application Tier Certifications
    OS      Product      Server      Status      
    XP      6.0.8.27.0 Patch 18      9.2      Desupported
    XP      6.0.8.27.0 Patch 18      10g      Desupported
    I read this as follows:
    Patch 18 was certified agains a 10g database in a webforms environment.
    No client server mentioned and Server 10g , so no 10gR2!
    I'm I right?
    Regards Erik

  • 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

  • Client server Imaging

    Hello,
    I need to make Client-Server Imaging, with JAI, I have two solutions. The first is to use RMI, the second IIP (there are two JAI operations which support IIP).
    I would like to ask, what are the main difference between those two ways or tell me how to make a IIP-server ... if someone can help me ...
    thanks.

    The key to your problem is to truly start thinking in Java.
    Hi, I'm doing the same work!
    i'm trying to do a viewer in java that support the iip
    server.
    if you can help me...
    thanks,
    Denis

Maybe you are looking for