Socket I/O : mismatching object/text between client/server

Suppose I'm listening on a socket for an object ...and I'm doing a ObjectInputStream.readObject() on it, but my client just opens an OutputStream and sends me text instead of an object (or vice-versa: Client sends object but server listens for text)? Is there a way of trapping such an error gracefully?

I'm not sure what error checking you think you need to do.
You will receive what was sent. TCP/IP guarantees that, and if it fails, you'll get an exception. I'm sure ejp can clear up my slop here. :-)
Once one application has received what the other has sent, it's up to it to validate it however appropriate. It doesn't matter if it's a String or an Object graph. If it's a String, you'll have to make sure it's in a valid format for whatever your protocol is. If it's an Object graph, you'll have to make sure that all the fields have valid values. The two tasks are essentially equivalent. Which one is easier comes down to what you're sending, and the complexity the protocol and its validation rules, which are ultimately driven by your business requirements.

Similar Messages

  • Sending object between client server with some class without serializable

    Hi friend,
    I need to send the object from server to client via ObjectInputStream and ObjectOutputStream, however, in these objects, some are implements by others, no source code provided, which haven't implement serizlizable, so does anyone can tell me what I can do?
    Thanks your concern.
    Cheers,
    Alva

    Anyone can help? It is urgent!
    Thanks,
    Alva

  • Sending a text file Client/Server problem

    Hi,
    I have two java classes (A.java and B.java). i would like to send the text file (something.txt) from A to B. Can somebody please show me how to do so? I know it is incomplete, but i really need help since im new to this. I dont know how to send and how to accept the file. Here is what i have so far:
    import java.net.*;
    import java.io.*;
    import java.lang.*;
    public class A {
            private static String hostname;                  //host name
            private static final int portA = 1111;           //source port number
            private static int portB;                        //destination port number
            private static ServerSocket s;
            private static Socket socket;
            private static BufferedReader br;    
            String fileName = "something.txt";
            public A () {
            public static void send() {
                    System.out.println("Send method");
                    try {
                        System.out.print("> Enter Hostname: ");
                     hostname = br.readLine();
                     System.out.print("> Enter Port Number: ");
                        portB = Integer.valueOf(br.readLine()).intValue();
                catch(IOException e){}
            public static void main(String args[]) throws IOException {
    import java.net.*;
    import java.io.*;
    import java.lang.*;
    public class B {
            private static String hostname;                  //host name
            private static final int portB = 2222;           //source port number
            private static ServerSocket s;
            private static Socket socket;
            private static BufferedReader br;    
            public B () {
            public static void recieve() {
                 //code to recieve the text file here?
            public static void main(String args[]) throws IOException {
    }I really appriciate any code to help me out. Thanks

    Check out the link shown below:
    http://forum.java.sun.com/thread.jsp?forum=33&thread=66616
    If that doesn't answer your question, search this site for Upload
    ;o)
    V.V.

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

  • 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

  • DHCP client\server request validation?

    Is there a way to have for example a client send a variable with it's BOOTP request that matches a DHCP server side variable to complete a trust relationship between client\server before handing out an address to the client?
    Basically the client would have an option set say "wagon21" and the server would have to have that value present. Then any clients that do not have the "wagon21" in their request would not be given a DHCP address.

    Hi,
    According to your description, my understanding is that you want to implement the function: DHCP server assign IP address to specific DHCP-enabled client.
    In general, a DHCP server is willing to assign IP address to all reachable DHCP enabled client that sends DHCPDISCOVER message. For Windows Server 2008 R2 and later version, DHCP Server can distribute DHCP leases based on MAC address by setting
    Filters – Allow/Deny. Detailed introduction and configuration steps, you may reference:
    https://technet.microsoft.com/en-us/library/dd759190.aspx
    Note that:
    1. If allow list is enabled, the DHCP server provides DHCP services only to clients whose MAC addresses are in the allow list
    2. If deny list is enabled, the DHCP server denies DHCP services only to clients whose MAC addresses are in the deny list.
    3. If both allow and deny lists enabled, the block list has precedence over the allow list. This means that the DHCP server provides DHCP services only to clients whose MAC addresses are in the allow list, provided that no corresponding matches are in the deny
    list. If a MAC address has been denied, the address is always blocked even if the address is on the allow list.
    Besides, you may configure DHCP user class, detailed information reference:
    https://support.microsoft.com/kb/240247/?wa=wsignin1.0
    Best Regards,
    Eve Wang
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact
    [email protected]

  • Client\server Forms

    Oracle Forms6i in a client\server environment is a great product that still works very well for us. We do not need (or want) a web-based solution. Our system only needs to support our in-house users (about 400 currently).
    I am very disappointed in the direction that Oracle is forcing us to go (web-based) if we want to stay with the Oracle tools that we know well. This isn't so much a request for help, it's more an attempt to communicate to the Oracle Forms manager(s) that going away from client\server is very disappointing to us and looks to be a bad business decision.

    Mark,
    I must appologize, but I though that things are easier to search and find on this forum. I tried for half an hour but wasn't able to spot the main thread ;-(
    The summary of it is that there was a big discussion on this forum after Oracle announced its desupport date for Forms and Reports client/server (sometime in July if I remember well). Along with this desupport date there was a discussion whether or not Oracle Forms supports XP. The initial decision of not supporting XP was reverted and XP now is supported since patch 13.
    For client/server the desupport date is January 1st 2005 for error correction and January 1st 2008 for extended assistance support. Thus Forms6i client/server will be around until end of 2007.
    Most discussions on this forum were about the cost going with moving Forms to the Web, especially keeping in mind that client/server runtime was for free.
    Another issue was the size of the Oracle9iAS installation which is 6GB all in all though Forms users may not use all the Oracle Application Server components.
    Last but not least, many customers didn't feel ready to move their applications to the Web in this period of time, especially those that run character mode applications.
    The installation issue gets fixed with the upcoming Oracle Application Server 10g which has a installation option that only installs the software required to run Forms and Reports.
    The migration is assisted by a Forms Migration Assistant in Forms9i as well as material that we compiled and published on OTN. The WebUtil library finally was developed to close the gap between client/server functionality and teh Web functionality.
    I can't talk about pricing, because this is not in the scope of my professional work, but OTN offered a special upgrade promotion for Forms users when moving their applications to teh Web.
    Client/server as it is in Forms6i will not come back, this is how it seems.
    There have been discussions on this forum if one could simulate client/server using the Forms Web components installed on a local client. Webstart was mentioned as one possible solution as it would allow you to have Forms applications started and run from an icon on the user desktop. Currently there are some investigations in Forms development going into this direction.
    The majority of customers that posted their opinion on the client/server desupport did not like the client/server desupport plan at all.
    The OTN forum postings where brought to Oracle senior management attention by Forms Product Managers monitoring this list.
    The benefit of a Web only version of Forms - and you may disagree - is integration with the J2EE stack Oracle has within Oracle9iAS and OracleAS 10g.
    J2EE is a technology that more and more customers evaluate for future development efforts. Having Forms integrating with J2EE applications(as seamlessly as possible)is the best way to make sure that Forms users can leverage their investment in the Forms technology. Even more, you can extend Forms applications with J2EE or have it communicating with it (the same applies to Reports)
    Many new features that we implemented in Forms6i and Forms9i worked on the Web only (SSO, Enterprise Manager monitoring, client side Java etc).
    Mark, hope that this summary gives you a good idea of what the discussions were about and that we do care of what customers do with Forms.
    Just in case that I missed an argument or presented it too positive (my memory is subjective and not perfect), I am sure that the forum members which already contributed to this posting will add additional comments. Others may join in too.
    Frank

  • HELP:USING CLIENT SERVER PROGRAM ON DIFF.MACHINES CONNECTED TO INTERNET?

    BELOW IS THE JAVA CODE FOR CLIENT & SERVER PROGRAM (TCP) USING SOCKET.
    I AM TRYING TO RUN CLIENT & SERVER PROGRAM ON 2 DIFFERENT MACHINES CONNECTED 2 INTERNET
    (1 RUNS SERVER.java & OTHER CLIENT.java).
    IS IT POSSIBLE WITH THE CODE WRITTEN BELOW?
    // Server.Java
    import java.net.*;
    import java.io.*;
    class Server {
    public static void main(String[] args) {
    boolean finished = false;
    try{
    ServerSocket listener = new ServerSocket(4444);
    while(!finished)
    {Socket to_client = listener.accept();
    OutputStream out = to_client.getOutputStream();
    PrintWriter pout = new PrintWriter(out, true);
    pout.println("Hello! this is server talking to you.");
    to_client.close();
    listener.close();
    }// end of try
    catch(Exception ie) {
    System.out.println(ie);
    //Client.Java
    import java.net.*;
    import java.io.*;
    class Client
    public static void main(String[] args)
    Socket client;
    String host="serverpcname";//host is assigned name of the server
    try
    {InetAddress adressen = InetAddress.getByName(host);
      client = new Socket(adressen,4444);
      BufferedReader scanf = new BufferedReader(new
      InputStreamReader(client.getInputStream()));
       String someString = scanf.readLine();
       System.out.println("From Server: "+someString);
      client.close();
    catch(Exception e)
    System.out.println(e);
    WHEN THE CODE IS EXECUTED(CLIENT.java ON 1 PC & SERVER.java on other) IT GIVES FOLLOWING EXCEPTIONS:
    java.net.UnknownHostException: serverpcname: serverpcname
    PLZ. GUIDE ME.
    THANKS IN ADVANCE.

    For a server to be accessible on the inetrnet it needs to have an externally visible IP address. For example, an address which starts with 192.168.1 is for internal use only can only be used by other machines on the same internal network. The server's firewall needs to allow the port you are using access and the client has to be able to lookup up the IP address either using the hosts file or via a DNS service. None of these things have anything to do with Java programming, so if you have any more questions I sugegst you try googling them or ask a forum which relates to these issues.
    The connection time out is due to the fact that there is no way to contact an inetrnal address over the inetrnet. The host unknwown means you haven't configured your PC to lookup that address. i.e. the host is unknown.

  • Socket communication between client and server

    Hi all,
    I am doing an assignment for communication between java client and java server using sockets. This communication is in the form of XML documents. I am facing a problem in this communication.
    Actually at Server side I'm creating an XML document(Document type object) using DocumentBuilderFactory in javax.xml.parsers package and transforming this Document into a stream using StreamResult.
    My code is :
    Transformer xmlTransformer = TransformerFactory.newInstance().newTransformer();
    StreamResult xmlString = new StreamResult(currentClientHandler.getSocketOutputStream());
    DOMSource xmlDocSource = new DOMSource(xmlDocument); // xmlDocument is Document type reference
    xmlTransformer.transform(xmlDocSource, xmlString);
    so, this xmlString(i.e. StreamResult) is passed directly into the output stream. Here I need to close() output stream after transform() call to help SAX parser to know about end of stream.
    Now at Client side, I am parsing this stream using SAX parser. It parses this correctly. But when sending some another data back to Server when client opens output stream, it given Socket closed exception. I know that closing input or output stream closes socket. But in my problem, I have to send data in streams and not by using files or byte[] etc.
    So what is nearest solution to problem ??
    Plz help me. Any kind of help will be greatly appreciated.

    hi
    thanks for ur reply.
    I didnt get any error msg while getting the back the datas.
    Actually i divided my application into two parts.
    My application will act as both server and client.
    server ll get the browser request and send to the client and the client will send that data to the c++ server.
    Im able to do that.and unable to get the data from server.
    Didnt get any error.
    can u tell me how to make an application to act as both client and server.
    I think im wrong in that part.
    thanks a lot

  • Questions on scripts, tables & transfer objects between clients.

    1. In script, how to use the same print program for two different layouts? with procedure.!
    2. Why cant sapscripts be client independent.?
    3. Want to maintain a table in dev server and if i update the data, it should simultanously update in Quality and Production servers. How? please explain in details.
    4. How to transfer object between clients.? explain.
    Points will be promptly rewarded for HELPFULL answers.!

    Hi!
    3. With SE01, you can create a transport request for all table entries.
    SE01 - Create button - Workbench request - Give description and save
    Select the created request and click on Display object list.
    Click on Display - Change button
    Insert line button
    ProgID: R3TR
    Object: TABU
    Object name: Z_YOUR_TABLE
    Double click on the table name
    Insert line
    Key: *
    Save everything
    Release the transport in SE10 transaction and transport with STMS transaction.
    Regards
    Tamá

  • Direct Connection between clients using sockets

    Hi, I'm a new user and i have a problem with sockets:
    The question is how can i directly connect two users that are already connected to a server in other machine???
    I mean
    user1 is connected to server
    user2 is connected to server
    user1 tries to communicate with user1 but don't want to use the server, and the server only provides the client1's ip
    I first thought to do this:
    user2 asks to server for the info of a client1-server waiting for connections, and i think it could work fine, but only if the ports are not closed by firewall, because client-server will be running in a transparent mode for user and user may not know anything about servers, sockets, ports, etc. the user only will work with a gui or something else and that's all
    Does anybody know what can i do to make this possible???
    PD
    Sorry for my bad English

    It can be implemented like you said. Make one of the clients open a serversocket and pass the ip and port number through the server to the other client with information on where to connect.
    If you're going to use direct connection between clients a lot then I would recommend that every client open a default serversocket at startup and register that information with the server and then every other client can ask the server for the ip and port to whatever client they wish to open a direct connection to.
    Be aware that clients often are behind NATs and firewalls, so if need to deal with those issues you got to use hole punching (http://en.wikipedia.org/wiki/hole_punching) - pref on a known port like 80 - and to deal with the less frequently used application firewalls you can use http encapsulation in addition.

  • Applet socket problem in client-server, urgent!

    Dear All:
    I have implemented a client server teamwork environment. I have managered to get the server running fine. The server is responsible for passing messages between clients and accessing Oracle database using JDBC. The client is a Java Applet. The code is like the following. The problem is when I try to register the client, the socket connection get java.security.AccessControlException: access denied(java.net.SocketPermission mugca.its.monash.edu.
    au resolve)
    However, I have written a Java application with the same socket connection method to connect to the same server, it connects to the server without any problem. Is it because of the applet security problem? How should I solve it? Very appreciate for any ideas.
    public class User extends java.applet.Applet implements ActionListener, ItemListener
    public void init()
    Authentication auth = new Authentication((Frame)anchorpoint);
    if(auth.getConnectionStreams() != null) {
    ConnectionStreams server_conn = auth.getConnectionStreams();
    // Authenticates the user and establishes a connection to the server
    class Authentication extends Dialog implements ActionListener, KeyListener {
    // Object holding information relevant to the server connection
    ConnectionStreams server_conn;
    final static int port = 6012;
    // Authenticates the user and establishes connection to the server
    public Authentication(Frame parent) {
    // call the class Dialog's constructor
    super(parent, "User Authentication", true);
    setLocation(parent.getSize().width/3, parent.getSize().height/2);
    setupDialog();
    // sets up the components of the dialog box
    private void setupDialog() {
    // create and set the layout manager
    //Create a username text field here
    //Create a password text field here
    //Create a OK button here
    public void actionPerformed(ActionEvent e) {
    authenticateUser();
    dispose();
    // returns the ConnectionStreams object
    public ConnectionStreams getConnectionStreams() {
    return(server_conn);
    // authenticates the user
    private void authenticateUser() {
    Socket socket;
    InetAddress address;
    try {
    // open socket to server
    System.out.println("Ready to connect to server on: " + port);
    socket = new Socket("mugca.its.monash.edu.au", port);
    address = socket.getInetAddress();
    System.out.println("The hostname,address,hostaddress,localhost is:" + address.getHostName() + ";\n" +
    address.getAddress() + ";\n" +
    address.getHostAddress() + ";\n" +
    address.getLocalHost());
    catch(Exception e) {
    displayMessage("Error occured. See console");
    System.err.println(e);
                                  e.printStackTrace();
    }

    Hi, there:
    Thanks for the help. But I don't have to configure the security policy. Instead, inspired by a message in this forum, I simply upload the applet to the HTTP server (mugca.its.monash.edu.au) where my won server is running. Then the applet is download from the server and running fine in my local machine.
    Dengsheng

  • Need Help for client - server - client question [Sockets]

    Hi
    I have read the http://java.sun.com/docs/books/tutorial/networking/sockets/index.html tutorial and made this Knock Knock Application.
    But now, I want that one client can view all the other clients which are connected to the server, and interract with a selected cleint over the server (client - server - client).
    But I have no idea how to build such a registration concept?
    A concrete hint (or link) how to realise this would be very helpful. I searched all the internet for examples, but I dont found a simple example.
    Thanks in advance
    greeds

    wSam,
    It appears that Sun considers RMI to be simpler, although less efficient than the alternative:
    http://java.sun.com/developer/technicalArticles/ALT/sockets/
    This article also talks about object serialization, which I am a fan of. Suppose that you want to send a data structure containing lots of information (like all connected users). You can actually pass an object (rather than text) across the network using ObjectOutputStream and receive it on the other end with ObjectInputStream. You might create your own Command class for passing objects between the client and server instead of using RMI. The Command class might hold flags that indicate which method should take place on the remote machine (i.e. send chess move command).

  • Client/server socket based application

    hi does anyone have example of client/server socket based application using Spring and Maven
    where application do the following
    Client sends a request with a path to any file on the server
    „h Server reads the file and responds back with the content
    „h Client outputs the content to the console
    am trying to follow this
    http://www2.sys-con.com/itsg/virtualcd/java/archives/0205/dibella/index.html
    http://syntx.io/a-client-server-application-using-socket-programming-in-java/
    am using java 6

    i have attempt code but i wht to do the following
    client/server socket based application that will read the content of a file and stream the content of the file to the client. The client must simply output the content of the file to the console using System.out. The client must be able to run in a standalone mode (non-network mode) or in a remote mode.
    Additionally the client must be designed in a way that i can print the output to a console but must be interchangeable where if requirements change i can persist the response to file or persist the response to a database.
    /* Server.java*/
    ///ifgetBoolen= true then...
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.sql.*;
    public class Server
        static String array[][];
        // STEP 1 a1  
        // Server socket
        ServerSocket listener;
        // STEP 1 a2 Client connection
        Socket client;
        ObjectInputStream in;
        ObjectOutputStream out;
        public void createConnection() throws IOException
                System.out.println("\nSERVER >>> Waiting for connection.....");
                client = listener.accept();
                String IPAddress = "" + client.getInetAddress();
                DisplayMessage("SERVER >>> Connected to " + IPAddress.substring(1,IPAddress.length()));
          public void runServer()
            // Start listening for client connections
            // STEP 2
            try
                listener = new ServerSocket(12345, 10);
                createConnection();
                  // STEP 3
    //              processConnection();
            catch(IOException ioe)
                DisplayMessage("SERVER >>> Error trying to listen: " + ioe.getMessage());
        private void closeConnection()
            DisplayMessage("SERVER >>> Terminating connections");
            try
                if(out != null && in != null)
                      out.close();
                    in.close();
                    client.close();                
            catch(IOException ioe)
                DisplayMessage("SERVER >>> Closing connections");
        public static void define2DArray(ResultSet RS, int Size)
            try
                ResultSetMetaData RMSD = RS.getMetaData();
                DisplayMessage("SERVER >>> Requested arraySize: " + Size);
                if (RS.next())
                    array = new String[Size][RMSD.getColumnCount()];
                    for (int Row = 0; Row < Size; Row++)
                        for (int Col = 0; Col < RMSD.getColumnCount(); Col++)
                            array[Row][Col] = new String();
                            array[Row][Col] = RS.getString(Col+1);
                            DisplayMessage(array[Row][Col] + " ");
                        RS.next();
                else
                    array = new String[1][1];
                    array[0][0] = "#No Records";
            catch (Exception e)
                DisplayMessage("SERVER >>> Error in defining a 2DArray: " + e.getMessage());  
        public static void DisplayMessage(final String IncomingSMS)
            System.out.println(IncomingSMS);
    //client
    * @author
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class ClientSystem
        static Socket server;
        static ObjectOutputStream out;
        static ObjectInputStream in;
        static String Response[][];
        static boolean IsConnected = false;
        static int Num = 0;
        public static void connectToServer() throws IOException
            server = new Socket("127.0.0.1", 12345);
    //        server = new Socket("000.00.98.00", 12345);
            String IPAddress = "" + server.getInetAddress();
            DisplayMessage("\nCLIENT >>> Connected to " + IPAddress.substring(1,IPAddress.length()));
        public static void getStreams() throws IOException
            out = new ObjectOutputStream(server.getOutputStream());
            out.flush();
              in = new ObjectInputStream(server.getInputStream());
              IsConnected = true;
              DisplayMessage("CLIENT >>> Got I/O streams");  
        public static void runClient()
            try
                connectToServer();
                getStreams();
                  DisplayMessage("CLIENT >>> Connection successfull....\n");
                  DisplayMessage("CLIENT >>> Want to talk to server");
            catch (IOException ioe)
                System.out.print("."+Num);
                Num++;
        public static void closeConnection()
            try
                out.close();
                in.close();
                server.close();  
            catch(IOException error)
                DisplayMessage("CLIENT >>> Could not close connections");
        public static void Start()
            System.out.print("\nCLIENT >>> Attempting connection.....");
            try
                IsConnected = false;
                while (IsConnected == false)
                    runClient();
                    if (IsConnected == false)
                        Thread.sleep(100);
            catch (Exception e)
                DisplayMessage("CLIENT >>> Attempting connection.....");
        public static String sendSMS(String sms)
            Response = new String[0][0];
            try
                DisplayMessage("CLIENT >>> " + sms);
                out.writeObject(sms);
                out.flush();
                Response = (String[][])in.readObject();
                DisplayMessage("CLIENT >>> Waiting for server to respond...");
                for (int Row = 0; Row < Response.length; Row++)
                    System.out.printf( "_SERVER >>> \t");
                    for (int Col = 0; Col < Response[Row].length; Col++)
                        //DisplayMessage( "_SERVER >>> " + Response[Row][Col] + " ");
                        System.out.printf( "%s\t", Response[Row][Col]);
                    System.out.println();
                DisplayMessage("CLIENT >>> Query processed successfully....\n");
            catch(ClassNotFoundException cnfe)
                DisplayMessage("CLIENT >>> Class not found for casting received object");
            catch(IOException ioe)
                reConnect();          
            catch (Exception sqle)
                DisplayMessage("CLIENT >>> Error sending query ??? " + sqle.getMessage());
            return "transmission successfull";
        public static void reConnect()
            try
                DisplayMessage("CLIENT >>> Connection was lost. Trying to reconnect...");
                closeConnection();
                Thread.sleep(100);
                IsConnected = false;
                while (IsConnected == false)
                    runClient();
                    Thread.sleep(200);
            catch (Exception e)
                DisplayMessage("CLIENT >>> Error trying to Re-Connect...");
        public static void DisplayMessage(final String IncomingSms)
            System.out.println(IncomingSms);
        System.out.printf("Isms: %s", IncomingSms);  ///naah.
        public static String[][] getResponse()
            return Response;
        public static String getResponse(int row, int col)
            return Response[row][col];
    how can i do below using above code
    The program must be able to work in a non-networked mode. In this mode, the server and client must run in the same VM and must perform no networking, must not use loopback networking i.e: no “localhost” or “127.0.0.1”, and must not involve the serialization of any objects when communicating between the client and server components.
    The operating mode is selected using the single command line argument that is permitted.
    imust use a socket connection and define a protocol. networking must be entirely bypassed in the non-network mode.

  • 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

Maybe you are looking for

  • IPhone 3GS Wont Start

    So.... I live in England, I recently visit Ireland where I turned on my iPhone. It wouldnt connect to a mobile network whilst I was in Ireland and even showed a message saying, IMEI not recognised. So, I get back to England tuen on my phone and it wo

  • Visual Basic Project

    I am currently making a valentine's day card for my programming class and I am suppose to create an algorithm to estimate the cost of the card. What I want the code to do is for every space the user enters in the richtextbox it adds one 5 cents to th

  • My PC crashed and I can't find the download email to use in my new PC. Ideas?

    I bought & downloaded Adobe XI. My PC crashed and I can't find the download email to use in my new PC. Ideas?

  • Premiere CC (2014) Blue Screen Restart During Export

    I have been having an issue where my PC will enter a blue screen and restart when exporting a video in the newest version of Premiere. I tried creating a smaller sequence, rather than the 15 minute export I was doing, and the same BSOD appeared durin

  • Grant privileges for future object?

    Hi all. Need help. 1) Bob grants object priveleges on cars to Anna 2) Anna renames cars to cars_old 3) Anna creates cars . 4) Bob has no privelges to cars:( How to grant privelges on 'created in future' tables?