Results 1 to 7 of 7
  1. #1
    kellaw is offline Member
    Join Date
    Oct 2008
    Posts
    24
    Rep Power
    0

    Unhappy Client Server socket problem - help needed

    ok this is a new thread which has the original program codes. Answers would be given reputation points if I get to solve this problem. It had been bugging me over the past week with little or no sleep:mad::(. The code might be a bit long so in exchange for your time, any post that is helpful gets reputation points.

    client
    general pastebin - client - post number 1217688
    server
    general pastebin - server - post number 1217691
    painter
    general pastebin - painter - post number 1217671

    The codes is real long so here is the explanation.

    This is a GUI program. It involves 2 client and a server. Both the clients are supposed to receive the int 99 from the server. The int is sent at line 127 "outputToClient1.writeInt(99);" and line 161 "outputToClient2.writeInt(99);" of server.java and it's supposed to be received by the 2 clients at line 358 "int sadsad = inputFromServer.readInt();".

    All I get when the program is executed is garbage numbers on both the clients. Any solution to this? All help is really appreciated. Actually the write and read Int are for testing as I can't get the message to the clients from the server.(Server line 175 & 177, client line 370)

    If you want the program, compile every file and start the server first, then start one client and select multiplayer, show to on and start game. then start the other client and select multiplayer, then start the game. It would print out in console.

  2. #2
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    7

    Default

    Not difficult, pending details. Just use one of two approches. First - the preferred one for now - is to convert the numbers for string for transmission, then do Int.parseString( .... ) on the other end. The other approach involves direct transmission of binary data, not ususlly the way to do it because it leads to the problem you already have showing up in other areas.

    pm me about the points, private statement to make on the matter for your use.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  3. #3
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,559
    Rep Power
    23

    Default

    garbage numbers on both the clients
    Can you post what the clients receive?


    There is way too much code in those links to work with. Can you strip the problem down to a single file with client and server in the same file and a main that starts both of them?

  4. #4
    kellaw is offline Member
    Join Date
    Oct 2008
    Posts
    24
    Rep Power
    0

    Default

    Nicholas parsing it into string wouldn't work as the 2 garbage number I get is at random and the number changes as i executes them several times.

    Norm - here's the mapping table with the line number involved. Sorry I have to put it into codes so it shows the correct formatting of the table


    Java Code:
    |Server            |Client 1          |Client 2          |
    |socket1 accept L66|connect L203->729 |                  |
    
    [COLOR="Red"]Client 1 connected and server sends the session no of 1 to client 1[/COLOR]
    |writeInt(1) L77   |readInt() L206    |                  |
    
    [COLOR="Red"]Client 1 selected multiplayer and show moves as on then start game. Client 1 
    sends int 2 to server to denote its multiplayer.[/COLOR]
    |readInt() L83     |writeInt(2) L340  |                  |
    
    [COLOR="Red"]Client 1 sends int 1 to server to denote showing moves is on.[/COLOR]
    |readInt() L116    |writeInt(1) L352  |                  |
    
    [COLOR="Red"]Server receives int 99 from client 1 as test and shows properly on the
    server’s console[/COLOR]
    |readInt() L124    |writeInt(99) L356 |                  |
    
    [COLOR="Red"]#Problem starts here - Server writes int 99 to client 1(should be successful 
    since the println after that did get printed) but client 1 doesn’t display it. It
    waits for client 2 to start and executed till the same place before it displays
    the garbage[/COLOR]
    |writeInt(99) L127 |readInt() L358    |                  |
    
    ==========================================================
    [COLOR="Red"]Client 1 waits for server to get a message which never reach because of the 
    previous problem while Client 2 starts up at this point[/COLOR]
    |socket2accept L132|                  |connect L203->729 |
    
    [COLOR="Red"]Client 2 connected and server sends the session no of 2 to client 2[/COLOR]
    |writeInt(2) L136  |                  |readInt() L206    |
    
    [COLOR="Red"]Server sends int 1 to client 2 to denote showing of moves[/COLOR]
    |writeInt(1) L140  |                  |readInt() L210    |
    
    [COLOR="Red"]Client 2 selects multiplayer(single is disabled) and clicks on start game. Server 
    receives int 2 from client 2 to denote multiplayer[/COLOR]
    |readInt() L154    |                  |writeInt(2) L340  |
    
    [COLOR="Red"]Server receives the test int 99 and prints it properly[/COLOR]
    |readInt() L158    |                  |writeInt(99) L356 |
    
    [COLOR="Red"]*Problem starts now when the server sends int 99 back to client and garbage 
    is printed again then it hangs there not accepting the message which the 
    server sends at line 175 & 177[/COLOR]
    |writeInt(99) L161 |                  |readInt() L358    |
    EDITED THE TABLE
    Last edited by kellaw; 10-03-2008 at 03:59 PM.

  5. #5
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,559
    Rep Power
    23

    Default

    What can anyone do with what you've posted?
    Where are the garbage numbers? Do your programs use println() to output the numbers? Can you post their output?
    Can you strip the problem down to a single file with client and server in the same file and a main that starts both of them?

  6. #6
    kellaw is offline Member
    Join Date
    Oct 2008
    Posts
    24
    Rep Power
    0

    Default

    See why its printing garbage integer when what is sent is int 99.

    garbage numbers is random integer eg 2343123 , 144324, 13243, 2241412

    yes. i use println() to print out the numbers received. that is why i know there are garbage numbers received.

    line 359 on the client prints it
    System.out.println("testing la "+sadsad);

    it should print "testing la 99" but instead its printing "testing la 112324"

    server output would be
    singleOrMulti(2)2
    showOrNot(1)1
    99
    test1
    test2
    show or not = 1
    multi from cl 2(2) = 2
    99
    test1
    test2
    Test send message
    message sent //denotes message was sent but client never receive it
    The secret pattern is : (4 rand nos)


    Client 1 output
    session = 1
    testing la 10324 //garbage instead of 99
    Test get message //and hangs

    Client 2 output
    session = 2
    can see sess2 (1) = 1
    testing la 10378 //garbage instead of 99
    Test get message //and hangs
    Last edited by kellaw; 10-03-2008 at 04:53 PM.

  7. #7
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,559
    Rep Power
    23

    Default

    Can you strip the problem down to a single file with client and server in the same file and a main that starts both of them?

    Without seeing the code, I can't help. The code your link goes to has to much extra code that is not part of the problem.
    Here is a sample client/server program that uses writeInt. Can you make it show your problem?
    Java Code:
    /*	
    Changed to use DataStream - send first a byte code describing what follows
    */
    //***************************************************************************
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import java.awt.Window.*;
    import java.awt.Label;
    
    public class ClientServerTest2 { // extends Thread {
    
       final public static byte StringCode = 1;
       final public static byte IntCode = 2;
    
       //*********************************************
       // Starts here 
       public static void main(String args[]){
          Server2.main(new String[]{});  // start the server
          final ClientGUI2 cGUI = new ClientGUI2();
    
          Runtime.getRuntime().addShutdownHook(new Thread(){
    //         @Override
             public void run() {           // NOT called???
                System.out.println("Shutting down");
                cGUI.shutdown();
             }
          });
       } // end main()
    } // end class ClientServerTest
    
    //**************************************************************************
    class ClientGUI2 extends JFrame  {
       Socket socket;
       DataInputStream in;
       DataOutputStream out;
       String host;
       int port = 1234;
    //   String message;
       private JFrame frame;
       private JTextField TeF = new JTextField(25);
       JTextArea TeA = new JTextArea(20,30);
       JScrollPane scroll = new JScrollPane(TeA);
       JButton b1 = new JButton("SEND");
       String fileName = " ";
       String savedFile = " ";
       JPanel west = new JPanel();
       JPanel east = new JPanel();
       JPanel south = new JPanel();
       MyJButtonListener2 myJButtonListener;
    
       final public static String ShutDownMsg = "ShuttingDown";
    
       private void setupGUI() {
          TeA.setEditable(false);             // output only
          TeA.setBackground(Color.lightGray);
          Container c = getContentPane();
          c.setLayout(new BorderLayout());
          c.add(BorderLayout.EAST,east);
          west.add(scroll);
          c.add(BorderLayout.WEST,west);
          south.add(TeF);
          south.add(b1);
          c.add(BorderLayout.SOUTH,south);
          myJButtonListener = new MyJButtonListener2(this);   //<<<<<<<<<<<
          b1.addActionListener(myJButtonListener);
          setSize(400,380);
          setVisible(true);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       }
       //----------------------------------------
       // Constructor
       ClientGUI2(){
          super("Client - Server test - DataStreams");
          setupGUI();
          getConnection();
          receiveMessage();
       }
    
       public void getConnection() {
          try {
             host = InetAddress.getLocalHost().getHostAddress();
             socket = new Socket(host,port);
             in = new DataInputStream(socket.getInputStream());
             out = new DataOutputStream(socket.getOutputStream());
    //         System.out.println("Client - getConn out=" + out);
          }catch(UnknownHostException e){
             System.out.println("Client - getConnection():" + e);
          }catch(IOException e) {
             System.out.println("Client - getConnection():" + e);
          }
       }
       
       final static int NoValue = -1;
    
       public void sendMessage(String message) {
    //      System.out.println("out= " + out);
          // Is message a number or text?
          int value = NoValue;             // To hold int value if found
          try {
             value = Integer.parseInt(message);  // test/get int value
          }catch(NumberFormatException nfe){
          }
          try {
             // Use different protocol for String vs int
             if(value == NoValue) {
                out.writeByte(ClientServerTest2.StringCode);        // code
                out.writeByte(message.length());  // length
                out.writeChars(message);          // data
             }else {
                out.writeByte(ClientServerTest2.IntCode);        // code
                out.writeInt(value);  // value
             }
             System.out.println("Client sent:- " + message);
          }catch(IOException x) {
             System.out.println("Client got ex");
             x.printStackTrace();
          }
       }
    
       public void receiveMessage() {
          String message = null;
          try {
             while (true){
                byte code = in.readByte();
                System.out.println("C-code=" + code);
                switch (code) {
                   case ClientServerTest2.StringCode:
                      int len = in.readByte();
                      StringBuffer sb = new StringBuffer(len);
                      for(int i=0; i < len; i++) {
                         char c = in.readChar();
                         sb.append(c);
                      }
                      message = sb.toString();
                      break;
                  case ClientServerTest2.IntCode:
                      break;
    
                   default:
                      message = "C-UNKNOWN CODE " + code;
                      System.out.println(message);
                } //end switch
    
                System.out.println("Client Received:" + message);
                // Show message and clear
                TeA.append(message + "\n");
                TeF.setText( ""); // clear input area
                TeF.requestFocus();
             } // end while()
          }catch(IOException e) {
             System.out.println("Client - receiveMessage():" + e);
          }
       }
    
       public void shutdown() {
          sendMessage(ShutDownMsg);
       }
       //---------------------------------------------
       class MyJButtonListener2 implements ActionListener{
          ClientGUI2 clientgui;
          MyJButtonListener2(ClientGUI2 cg) {
             clientgui = cg;    // save
          }
          public void actionPerformed(ActionEvent e){
             if(e.getActionCommand().equals("SEND")) {
                clientgui.sendMessage(TeF.getText());
             }else{
                System.out.println("unknown ae=" + e);
             }
          }
       }
    } // end class ClientGUI2
    
    //***************************************************************************
    class Server2  extends Thread {
       ServerSocket server;
       Socket connection;
       
       DataInputStream in;
       DataOutputStream out;
    
       int port = 1234;
    //   String message;
       
       public static void main(String args[]) {
          Server2 server = new Server2();
          server.start();
       }
    
       public void run() {
          getConnection();
          recieveMessage();
       }
       private void getConnection() {
          try    {
             server = new ServerSocket(port);
             System.out.println("Waiting for client...");
             connection = server.accept();
             System.out.println("Server got conection: " + connection);
             in = new DataInputStream(connection.getInputStream());
             out = new DataOutputStream(connection.getOutputStream());
          }    catch(IOException e)   {
             System.out.println("Server - getConnection();" + e);
          }
       }
       
       private void recieveMessage() {
          try {
             String message = null;
             while(true) {
                byte code = in.readByte();
                System.out.println("S-code=" + code);
                switch (code) {
                   case ClientServerTest2.StringCode:
                      int len = in.readByte();
                      StringBuffer sb = new StringBuffer(len);
                      for(int i=0; i < len; i++) {
                         char c = in.readChar();
                         sb.append(c);
                      }
                      message = sb.toString();
                      break;
                  case ClientServerTest2.IntCode:
                      int value = in.readInt();
                      message = "int("+value+")";
                      break;
    
                   default:
                      message = "S-unknown code: " + code;
                      System.out.println(message);
                } //end switch
                System.out.println("Server - recMsg msg="   + message);
                sendMessage("Returned:" + message); // send it back
             } // end while()
          } catch(IOException e) {
             System.out.println("Server -receiveMessage():" + e);
          }
       }
       
       private void sendMessage(String message){
          try{
             out.writeByte(ClientServerTest2.StringCode); // code
             out.writeByte(message.length());  // length
             out.writeChars(message);          // data
          }catch(IOException x) {
             System.out.println("Server got ex");
             x.printStackTrace();
          }
       }
    } // end class Server

Similar Threads

  1. Server socket - send image to client
    By Hinty in forum Networking
    Replies: 2
    Last Post: 03-14-2009, 07:39 AM
  2. Replies: 4
    Last Post: 10-02-2008, 06:32 PM
  3. passing info between server/client problem
    By DarkBlaze in forum New To Java
    Replies: 13
    Last Post: 07-24-2008, 03:14 AM
  4. Identify Client in Socket Client Server Application
    By masadjie in forum Networking
    Replies: 1
    Last Post: 12-20-2007, 09:18 AM
  5. client-server communication problem
    By revathi17 in forum New To Java
    Replies: 1
    Last Post: 08-09-2007, 02:21 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •