Problems with sockets...

I start the Server program and after i start the Client program.
But the Client program is blocked, I just can see the JFrame maximized, I can't even see the the full GUI, the Client program just shows a JFrame that I cant' use.
If I send messagens to Client using the Server program, I just can see these messages after I close Server program, so after Server program is closed, the Client program is ready to use!
Why that?
Here's the Server class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class Server implements ActionListener, KeyListener {
   private JFrame janela = new JFrame("Server");
   private String nome;
   private JPanel conversaPanel = new JPanel();
   private JPanel mensagemPanel = new JPanel();
   private JTextArea conversaTextArea = new JTextArea(41, 75);
   private JScrollPane conversaScrollPane = new JScrollPane(conversaTextArea);
   private JTextField mensagemTextField = new JTextField(70);
   private JButton mensagemButton = new JButton("Send Message");
   private ServerSocket serverSocket = null;
   private Socket socket;
   private BufferedReader entrada;
   private PrintStream saida;
   /** Creates a new instance of Server */
   public Server(String nome) {
      this.nome = nome;
      janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      conversaPanel.add(conversaScrollPane);
      mensagemPanel.add(mensagemTextField);
      mensagemPanel.add(mensagemButton);
      janela.add(conversaPanel, BorderLayout.WEST);
      janela.add(mensagemPanel, BorderLayout.SOUTH);
      janela.setExtendedState(JFrame.MAXIMIZED_BOTH);
      janela.setVisible(true);
      // Listeners.
      mensagemButton.addActionListener(this);
      mensagemTextField.addKeyListener(this);
      try {
         serverSocket = new ServerSocket(1000);
         socket = serverSocket.accept();
         entrada = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         saida = new PrintStream(socket.getOutputStream());
         while(true) {
            String s = entrada.readLine();
            if(! s.trim().equals(""))
               conversaTextArea.setText(conversaTextArea.getText() + "\n" + s);
      catch(IOException ioe) {
         System.out.println(ioe);   
   public void keyPressed(KeyEvent ke) {
      if(ke.getKeyCode() == KeyEvent.VK_ENTER && ! mensagemTextField.getText().trim().equals("")) {
         conversaTextArea.setText(conversaTextArea.getText() + "\n" + nome + " : " + mensagemTextField.getText());   
         saida.println(nome + " : " + mensagemTextField.getText());
         mensagemTextField.setText("");
   public void actionPerformed(ActionEvent ae) {
      Object objeto = ae.getSource();  
      if(objeto == mensagemButton && ! mensagemTextField.getText().trim().equals("")) {
         conversaTextArea.setText(conversaTextArea.getText() + "\n" + nome + " digitou: " + mensagemTextField.getText());   
         saida.println(nome + " : " + mensagemTextField.getText());
         mensagemTextField.setText("");
   public static void main(String[] args) {
      Server s = new Server("Servidor");
}Now the Client class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class Client implements ActionListener, KeyListener {
   private JFrame janela = new JFrame("Client");
   private JPanel conversaPanel = new JPanel();
   private JPanel mensagemPanel = new JPanel();
   private JTextArea conversaTextArea = new JTextArea(41, 75);
   private JScrollPane conversaScrollPane = new JScrollPane(conversaTextArea);
   private JTextField mensagemTextField = new JTextField(70);
   private JButton mensagemButton = new JButton("Enviar Mensagem");
   private Socket socket;
   private BufferedReader entrada;
   private PrintStream saida;
   private String nome;
   private String ip;
   /** Creates a new instance of Client */
   public Client(String ip, String nome) {
      this.nome = nome;
      janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      conversaPanel.add(conversaScrollPane);
      mensagemPanel.add(mensagemTextField);
      mensagemPanel.add(mensagemButton);
      janela.add(conversaPanel, BorderLayout.WEST);
      janela.add(mensagemPanel, BorderLayout.SOUTH);
      janela.setVisible(true);
      janela.setExtendedState(JFrame.MAXIMIZED_BOTH);
      // Listeners.
      mensagemButton.addActionListener(this);
      mensagemTextField.addKeyListener(this);
      try {
         socket = new Socket(ip, 1000);
         entrada = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         saida = new PrintStream(socket.getOutputStream());
         while(true) {
            String s = entrada.readLine();
            if(! s.trim().equals(""))              
               conversaTextArea.setText(conversaTextArea.getText() + "\n" + s);
      catch(IOException ioe) {
         System.out.println(ioe);   
   public void keyPressed(KeyEvent ke) {
      if(ke.getKeyCode() == KeyEvent.VK_ENTER && ! mensagemTextField.getText().trim().equals("")) {
         conversaTextArea.setText(conversaTextArea.getText() + "\n" + nome + " : " + mensagemTextField.getText());   
         saida.println(nome + " : " + mensagemTextField.getText());
         mensagemTextField.setText("");
   public void actionPerformed(ActionEvent ae) {
      Object objeto = ae.getSource();  
      if(objeto == mensagemButton && ! mensagemTextField.getText().trim().equals("")) {
         conversaTextArea.setText(conversaTextArea.getText() + "\n" + nome + " digitou: " + mensagemTextField.getText());   
         saida.println(nome + " : " + mensagemTextField.getText());
         mensagemTextField.setText("");
}   Here's the class wich calls the Client class:
public class Login implements ActionListener {
   private JFrame janela = new JFrame("Nick");
   private JLabel ipLabel = new JLabel("IP Server: ");
   private JLabel apelidoLabel = new JLabel("Nick: ");
   private JTextField ipTextField = new JTextField(15);
   private JTextField apelidoTextField = new JTextField(10);
   private JButton okButton = new JButton("OK");
   private String ip;
   private Client client;
   /** Creates a new instance of Login */
   public Login() {
      janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      janela.setLayout(new FlowLayout());
      janela.add(ipLabel);
      janela.add(ipTextField);
      janela.add(apelidoLabel);
      janela.add(apelidoTextField);
      janela.add(okButton);
      janela.pack();
      janela.setResizable(false);
      Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
      int largura = d.width;
      int altura = d.height;
      janela.setBounds((largura - janela.getWidth()) / 2, (altura - janela.getHeight()) / 2, janela.getWidth(), janela.getHeight());
      janela.setVisible(true);
      // Listeners.
      okButton.addActionListener(this);
   public void actionPerformed(ActionEvent ae) {
      Object objeto = ae.getSource();
      if(objeto == okButton && ! ipTextField.getText().trim().equals("") && ! apelidoTextField.getText().trim().equals("")) {
         janela.setVisible(false);
         client = new Client(ip, apelidoTextField.getText());
   public static void main(String[] args) {
      Login l = new Login();
}Help, anyone?
Thanks.

You need to construct, accept, and do I/O on sockets in a separate thread from the AWT thread (the thread the ActionListener runs in).
Otherwise you will stall the GUI.

Similar Messages

  • Problem with socket packaging

    There seems to be a problem with the plastic cpu clip i work as a tech in a computer store we build many systems with msi boards, the plastic clip on the 915G series most times has fallen off and pins in the cpu socket have been damaged.
    You should use a plastic insert under the cpu hood to prevent it from falling off.

    Quote
    Not sure either why DelUK thinks this is not a suitable topic for this forum.
    Probably because Del interpreted "You should use a plastic insert under the cpu hood to prevent it from falling off." to mean that "You" was MSI, and not the members of this forum. Oddly enough, I interpreted this the same way.  I don't see where Del indicated the topic was not suitable, though.
    As Del said, and as mentioned in the Forum Rules, MSI does not participate here. If you feel there is a manufacturing problem, contact MSI directly.

  • Problem with Socket Sever

    Hello,
    I have a problem with a java socket.
    I have a server application that generate random number.
    I my client application, I connected to server application and red the random number.
    My problem is in my application client only read one time. After this, the socket server application close.
    How to do the server socket wait a new request from my client application?

    Put your accept in a while ....
    while (!this.interrupted()) {
    Socket socket;
    try {
    socket = serverSocket.accept();
    if (this.isInterrupted()) {
    return;
    new ClientConnection(); ///////Do your thing here ...
    } catch (IOException e) {
    return;
    HOPE this helps

  • Problem with socket cross domain

    Hi guys,
    This is my cross domain file:
    <?xml version="1.0"?>
    <!DOCTYPE cross-domain-policy SYSTEM "/xml/dtds/cross-domain-policy.dtd">
    <!-- Policy file for xmlsocket://socks.example.com -->
    <cross-domain-policy>
       <site-control permitted-cross-domain-policies="*"/>
       <allow-access-from domain="localhost" to-ports="80" />
    </cross-domain-policy>
    I am placing it in my server.
    From flex i am running this:
    Security.loadPolicyFile("my server address");
    And yet I am getting this event:
    SecurityErrorEvent type="securityError" bubbles=false cancelable=false eventPhase=2 text="Error #2048"
    What can I do?

    Hello ILikeMyScreenNameNdCoffee,
    I had the same problem with XMLSocket and I used a policy server that runs
    on the remote server on port 843 and from Flex I load file before connecting
    the xmlsocket Security.loadPolicyFile("my server address:843"). If you want
    I can upload a version of my policy server or you can use the server policy
    from here
    http://www.broculos.net/tutorials/how_to_make_a_multi_client_flash_java_server/20080320/en
    Also you can read here more about file policy:
    http://www.adobe.com/devnet/flashplayer/articles/fplayer9_security_04.html.
    On Thu, Aug 19, 2010 at 5:40 PM, ILikeMyScreenNameNdCoffee <[email protected]

  • Problem with socket permissions!

    Hi All!
    I'm developing an applet that displays an image after downlading it from a server; this server is different from the server I download the applet from, so I have problems with security. In fact I get the following exception:
    java.security.AccessControlException: access denied (java.net.SocketPermission 172.16.1.22:8080 connect,resolve)
    I'm using:
    - Java Plugin 1.3;
    - Netscape 7.0;
    - IE 6;
    I've tried to self-sign the applet but with no results (maybe I cannot use selfsigned certificate with java plugin 1.3);
    After that I've created a new policy file ("MyPolicy" file)and mentioned it into:
    C:\Program Files\JavaSoft\JRE\1.3.1_03\lib\security\java.policy
    but it didn't resolve my problem (maybe I'm doing something wrong in creating my policy file??!!).
    Which steps do I have to follow in order to make my applet connect to images server without security problems?
    Thanks so much in advance,
    Carlo

    1.     Compile the applet
    2.     Create a JAR file
    3.     Generate Keys
    4.     Sign the JAR file
    5.     Export the Public Key Certificate
    6.     Import the Certificate as a Trusted Certificate
    7.     Create the policy file
    8.     Run the applet
    Susan
    Susan bundles the applet executable in a JAR file, signs the JAR file, and exports the public key certificate.
    1.     Compile the Applet
    In her working directory, Susan uses the javac command to compile the SignedAppletDemo.java class. The output from the javac command is the SignedAppletDemo.class.
    javac SignedAppletDemo.java
    2.     Make a JAR File
    Susan then makes the compiled SignedAppletDemo.class file into a JAR file. The -cvf option to the jar command creates a new archive (c), using verbose mode (v), and specifies the archive file name (f). The archive file name is SignedApplet.jar.
    jar cvf SignedApplet.jar SignedAppletDemo.class
    3.     Generate Keys
    Susan creates a keystore database named susanstore that has an entry for a newly generated public and private key pair with the public key in a certificate. A JAR file is signed with the private key of the creator of the JAR file and the signature is verified by the recipient of the JAR file with the public key in the pair. The certificate is a statement from the owner of the private key that the public key in the pair has a particular value so the person using the public key can be assured the public key is authentic. Public and private keys must already exist in the keystore database before jarsigner can be used to sign or verify the signature on a JAR file.
    In her working directory, Susan creates a keystore database and generates the keys:
    keytool -genkey -alias signFiles -keystore susanstore -keypass kpi135 -dname "cn=jones" -storepass ab987c
    This keytool -genkey command invocation generates a key pair that is identified by the alias signFiles. Subsequent keytool command invocations use this alias and the key password (-keypass kpi135) to access the private key in the generated pair.
    The generated key pair is stored in a keystore database called susanstore (-keystore susanstore) in the current directory, and accessed with the susanstore password (-storepass ab987c).
    The -dname "cn=jones" option specifies an X.500 Distinguished Name with a commonName (cn) value. X.500 Distinguished Names identify entities for X.509 certificates.
    You can view all keytool options and parameters by typing:
    keytool -help
    4.     Sign the JAR File
    JAR Signer is a command line tool for signing and verifying the signature on JAR files. In her working directory, Susan uses jarsigner to make a signed copy of the SignedApplet.jar file.
    jarsigner -keystore susanstore -storepass ab987c -keypass kpi135 -signedjar SSignedApplet.jar SignedApplet.jar signFiles
    The -storepass ab987c and -keystore susanstore options specify the keystore database and password where the private key for signing the JAR file is stored. The -keypass kpi135 option is the password to the private key, SSignedApplet.jar is the name of the signed JAR file, and signFiles is the alias to the private key. jarsigner extracts the certificate from the keystore whose entry is signFiles and attaches it to the generated signature of the signed JAR file.
    5.     Export the Public Key Certificate
    The public key certificate is sent with the JAR file to the whoever is going to use the applet. That person uses the certificate to authenticate the signature on the JAR file. To send a certificate, you have to first export it.
    The -storepass ab987c and -keystore susanstore options specify the keystore database and password where the private key for signing the JAR file is stored. The -keypass kpi135 option is the password to the private key, SSignedApplet.jar is the name of the signed JAR file, and signFiles is the alias to the private key. jarsigner extracts the certificate from the keystore whose entry is signFiles and attaches it to the generated signature of the signed JAR file.
    5: Export the Public Key Certificate
    The public key certificate is sent with the JAR file to the whoever is going to use the applet. That person uses the certificate to authenticate the signature on the JAR file. To send a certificate, you have to first export it.
    In her working directory, Susan uses keytool to copy the certificate from susanstore to a file named SusanJones.cer as follows:
    keytool -export -keystore susanstore -storepass ab987c -alias signFiles -file SusanJones.cer
    Ray
    Ray receives the JAR file from Susan, imports the certificate, creates a policy file granting the applet access, and runs the applet.
    6.     Import Certificate as a Trusted Certificate
    Ray has received SSignedApplet.jar and SusanJones.cer from Susan. He puts them in his home directory. Ray must now create a keystore database (raystore) and import the certificate into it. Ray uses keytool in his home directory /home/ray to import the certificate:
    keytool -import -alias susan -file SusanJones.cer -keystore raystore -storepass abcdefgh
    7.     Create the Policy File
    The policy file grants the SSignedApplet.jar file signed by the alias susan permission to create newfile (and no other file) in the user's home directory.
    Ray creates the policy file in his home directory using either policytool or an ASCII editor.
    keystore "/home/ray/raystore";
    // A sample policy file that lets a JavaTM program
    // create newfile in user's home directory
    // Satya N Dodda
    grant SignedBy "susan"
         permission java.security.AllPermission;
    8.     Run the Applet in Applet Viewer
    Applet Viewer connects to the HTML documents and resources specified in the call to appletviewer, and displays the applet in its own window. To run the example, Ray copies the signed JAR file and HTML file to /home/aURL/public_html and invokes Applet viewer from his home directory as follows:
    Html code :
    </body>
    </html>
    <OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    width="600" height="400" align="middle"
    codebase="http://java.sun.com/products/plugin/1.3/jinstall-13-win32.cab#Version=1,3,1,2">
    <PARAM NAME="code" VALUE="SignedAppletDemo.class">
    <PARAM NAME="archive" VALUE="SSignedApplet.jar">
    <PARAM NAME="type" VALUE="application/x-java-applet;version=1.3">
    </OBJECT>
    </body>
    </html>
    appletviewer -J-Djava.security.policy=Write.jp
    http://aURL.com/SignedApplet.html
    Note: Type everything on one line and put a space after Write.jp
    The -J-Djava.security.policy=Write.jp option tells Applet Viewer to run the applet referenced in the SignedApplet.html file with the Write.jp policy file.
    Note: The Policy file can be stored on a server and specified in the appletviewer invocation as a URL.
    9.     Run the Applet in Browser
    Download JRE 1.3 from Javasoft

  • I suppose it is the problem with socket connection,Please help

    Hi,
    I'm trying to build a chat server in Java on Linux OS.I've created basically 2 classes in the client program.The first one shows the login window.When we enter the Login ID & password & click on the ok button,the data is sent to the server for verification.If the login is true,the second class is invoked,which displays the messenger window.This class again access the server
    for collecting the IDs of the online persons.But this statement which reads from the server causes an exception in the program.If we invoke the second class independently(ie not from 1st class) then there is no problem & the required data is read from the server.Can anyone please help me in getting this program right.I'm working on a p4 machine with JDK1.4.
    The Exceptions caused are given below
    java.net.SocketException: Connection reset by peer: Connection reset by peer
    at java.net.SocketInputStream.SocketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:119)
         at java.io.InputStreamReader$CharsetFiller.readBytes(InputStreanReader.java :339)
         at java.io.InputStreamReader$CharsetFiller.fill(InputStreamReader.java:374)
         at java.io.InputStreamReader.read(InputStreamReader.java:511)
         at java.io.BufferedReader.fill(BufferedReader.java:139)
         at java.io.BufferedReader.readLine(BufferedReader.java:299)
         at java.io.BufferedReader.readLine(BufferedReader.java:362)
         at Login.LoginData(Login.java:330)
         at Login.test(Login.java:155)
         at Login$Buttonhandler.actionPerformed(Login.java:138)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1722)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:17775)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:4141)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:253)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:261)
         at java.awt.Component.processMouseEvent(Component.java:4906)
         at java.awt.Component.processEvent(component.java:4732)
         at java.awt.Container.processEvent(Container.java:1337)
         at java.awt.component.dispatchEventImpl(Component.java:3476)
         at java.awt.Container.dispatchEventImpl(Container.java:1399)
         at java.awt.Component.dispatchEvent(Component.java:3343)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3302)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3014)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2967)
         at java.awt.Container.dispatchEventImpl(Container.java:1373)
         at java.awt.window.dispatchEventImpl(Window.java:1459)
         at java.awt.Component.dispatchEvent(Component.java:3343)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:439)
         at java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:131)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
         My program looks somewhat like this :
    1st class definition:
    public class Login extends Jframe// Login is the name of the first class;
    Socket connection;
    DataOutputStream outStream;
    BufferedReader inStream;
    Frame is set up here
    public class Buttonhandler implements ActionListener
    public void actionPerformed(ActionEvent e) {
    String comm = e.getActionCommand();
    if(comm.equals("ok")) {
    check=LoginCheck(ID,paswd);
    test();
    public void test() //checks whether the login is true
    if(check)
    new Messenger(ID);// the second class is invoked
    public boolean LoginCheck(String user,String passwd)
    //Enter the Server's IP & port below
    String destination="localhost";
    int port=1234;
    try
    connection=new Socket(destination,port);
    }catch (UnknownHostException ex){
    error("Unknown host");
    catch (IOException ex){
    ex.printStackTrace ();
    error("IO error creating socket ");
    try{
    inStream = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    outStream=new DataOutputStream(connection.getOutputStream());
    }catch (IOException ex){
    error("IO error getting streams");
    ex.printStackTrace();
    System.out.println("connected to "+destination+" at port "+port+".");
    BufferedReader keyboardInput=new BufferedReader(new InputStreamReader(System.in));
    String receive=new String();
    try{
    receive=inStream.readLine();
    }catch(IOException ex){ error("Error reading from server");}
    if(receive.equals("Logintrue"))
    check=true;
    else
    check=false;
    try{
    inStream.close();
    outStream.close();
    connection.close();
    }catch (IOException ex){
    error("IO error closing socket");
    return(check);
    // second class is defined below
    public class Messenger
    Socket connect;
    DataOutputStream outStr;
    BufferedReader inStr;
    public static void main(String args[])
    { Messenger mes = new Messenger(args[0]);}
    Messenger(String strg)
    CreateWindow();
    setupEvents();
    LoginData(strg);
    fram.show();
    void setupEvents()
    fram.addWindowListener(new WindowHandler());
    login.addActionListener(new MenuItemHandler());
    quit.addActionListener(new MenuItemHandler());
    button.addActionListener(new Buttonhandle());
    public void LoginData(String name)
    //Enter the Server's IP & port below
    String dest="localhost";
    int port=1234;
    int r=0;
    String str[]=new String[40];
    try
    connect=new Socket(dest,port);
    }catch (UnknownHostException ex){
    error("Unknown host");
    catch (IOException ex){
    ex.printStackTrace ();
    error("IO error creating socket ");
    try{
    inStr = new BufferedReader(new InputStreamReader(connect.getInputStream()));
    outStr=new DataOutputStream(connect.getOutputStream());
    }catch (IOException ex){
    error("IO error getting streams");
    ex.printStackTrace();
    String codeln=new String("\n");
    try{
    outStr.flush();
    outStr.writeBytes("!@*&!@#$%^");//code for sending logged in users
    outStr.writeBytes(codeln);
    outStr.write(13);
    outStr.flush();
    String check="qkpltx";
    String receive=new String();
    try{
    while((receive=inStr.readLine())!=null) //the statement that causes the exception
    if(receive.equals(check))
    break;
    else
         str[r]=receive;
         r++;
    }catch(IOException ex){ex.printStackTrace();error("Error reading from socket");}
    catch(NullPointerException ex){ex.printStackTrace();}
    } catch (IOException ex){ex.printStackTrace();
    error("Error reading from keyboard or socket ");
    try{
    inStr.close();
    outStr.close();
    connect.close();
    }catch (IOException ex){
    error("IO error closing socket");
    for(int l=0,k=1;l<r;l=l+2,k++)
    if(!(str[l].equals(name)))
    stud[k]=" "+str[l];
    else
    k--;
    public class Buttonhandle implements ActionListener
    public void actionPerformed(ActionEvent e) {
    //chat with the selected user;
    public class MenuItemHandler implements ActionListener
    public void actionPerformed(ActionEvent e)
    String cmd=e.getActionCommand();
    if(cmd.equals("Disconnect"))
    //Disconnect from the server
    else if(cmd.equals("Change User"))
         //Disconnect from the server & call the login window
    else if(cmd.equals("View Connection Details"))
    //show connection details;
    public class WindowHandler extends WindowAdapter
    public void windowClosing(WindowEvent e){
    //Disconnect from server & then exit;
    System.exit(0);}
    I�ll be very thankful if anyone corrects the mistake for me.Please help.

    You're connecting to the server twice. After you've successfully logged in, pass the Socket to the Messenger class.
    public class Messenger {
        Socket connect;
        public static void main(String args[]) {
            Messenger mes = new Messenger(args[0]);
        Messenger(Socket s, String strg) {
            this.connect = s;
            CreateWindow();
            setupEvents();
            LoginData(strg);
            fram.show();
    }

  • Problem with socket responses with flex

    Hi, I am using the code below to connect to an IMAP server.
    When I telnet to the server and use the commands that I am sending in the code, the rsponses are correct.
    However, when I run the code below, I only obtain the ready and logged in responses as shown below.
    Any ideas why I am not receiving the full set of responses from the socket?
    Thanks in advance fro your advice.
    The following is the output from the code:
    +++++++++++++++++ START SENDING IMAP DATA +++++++++++++++++++++++++
    sent: . login user1 myPassword
    sent: . status INBOX (messages)
    sent: . select INBOX
    +++++++++++++++++ END SENDING IMAP DATA +++++++++++++++++++++++++
    ++++++++ [IMAP START]
    Response is: * OK Dovecot ready.
    [IMAP END] +++++++++
    ++++++++ [IMAP START]
    Response is: . OK Logged in.
    [IMAP END] +++++++++
    The code is:
    <?xml version="1.0" encoding="utf-8"?>
    <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
       xmlns:s="library://ns.adobe.com/flex/spark"
       xmlns:mx="library://ns.adobe.com/flex/mx"
       applicationComplete="init()">
    <fx:Declarations>
    <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <fx:Script>
    <![CDATA[
    public var dataStr:String;
    private var socket:Socket;
    private var serverURL:String= "dead.org";
    private var serverPort:int = 143;
    private var serverResponse:ByteArray = new ByteArray();
    private function init():void
      this.serverURL = serverURL;
      this.serverPort = serverPort;
      socket = new Socket();
      socket.addEventListener(ProgressEvent.SOCKET_DATA,handleNewIMAPData); //Event when socket receives new data
      this.connectToServer();
      sendIMAPdata();
    private function sendString(dataStr:String):void
      var bytes:ByteArray = new ByteArray();
      bytes.writeMultiByte(dataStr, "UTF-8");
      socket.writeBytes(bytes);
      socket.flush();
      trace("sent: " + dataStr);
    public function sendIMAPdata():void
      trace("\t +++++++++++++++++ START SENDING IMAP DATA +++++++++++++++++++++++++");
      dataStr =". login user1 myPassword" + "\r\n";
      sendString(dataStr);
      dataStr =". status INBOX (messages)" + "\r\n";
      sendString(dataStr);
      dataStr =". select INBOX" + "\r\n";
          sendString(dataStr);
      trace("\t +++++++++++++++++ END SENDING IMAP DATA +++++++++++++++++++++++++");
    private function handleNewIMAPData(event:ProgressEvent):void
      var numBytes:int = socket.bytesAvailable;
      serverResponse = new ByteArray();
      while(socket.bytesAvailable)
        var byte:int = socket.readUnsignedByte();
    serverResponse.writeByte(byte);
      var response:String = serverResponse.toString();
      trace(" ++++++++ [IMAP START]\n Response is: " + response + "[IMAP END] +++++++++\n");
    private function connectToServer():void
      socket.connect(serverURL, serverPort);
    ]]>
    </fx:Script>
    </s:WindowedApplication>

    When I run telnet, the console responses are the same as the tcpdump messages.
    When I run the program, the messages from tcpdump match the messages in my trace statements.
    The messages from telnet and running the program are different:-)
    I can only assume (at the moment) that I am sending multiple messages too quickly(?), but I did a quick and dirty big "for loop" to slow down the sending of subsequent messages, but with no resulting change in the programs behaviour.
    So, still thinking about the problem -  unfortunately.

  • Problem with socket programming(Vista)

    I'm not sure if this has something to do with windows vista.
    I wrote simple echo client and server programs and the client program contains these lines
    String hostname="172.16.54.22"; //My comp's IP
    int portNo=6666;
    mySocket=new Socket(hostname, portNo);
    Now the problem is that the client program is able to communicate with the server only when I run both of them in xp machines or if I run the server in vista and client in xp. The client is not able to connect to the server when both the client and server are running in a vista machine or if the server is running in xp and client in vista.
    It'd be nice if any of you could throw some light on this issue.
    PS:
    It doesn't work even if I turn the firewall off
    The programs work well when I give hostname="localhost" or hostname="127.0.0.1"
    Here are my programs
    //EchoClient.java
    import java.io.*;
    import java.net.*;
    import java.util.*;
    class EchoClient
         public static void main(String args[])
              String hostname="172.16.54.25"; //My ip address
              int portNo=6666;
              //if(args[1]
              //PrintWriter out=null;
              Socket mySocket=null;
              BufferedReader networkIn=null;
              BufferedReader userIn=null;
              PrintWriter sockOut=null;
              try
                   mySocket=new Socket(hostname, portNo);
                   networkIn=new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
                   userIn=new BufferedReader(new InputStreamReader(System.in));
                   sockOut= new PrintWriter(mySocket.getOutputStream());
                   System.out.println("Connected to Echo Server\n");
                   System.out.println("Enter a series of lines (\"end\" to exit)\n");
                   while(true)
                        String myLine=userIn.readLine();
                   //     System.out.println(myLine);
                        if(myLine.equals("end"))
                             break;
                        sockOut.println(myLine);
                        sockOut.flush();
                        System.out.println(networkIn.readLine());
              catch(IOException exc)
                   System.err.println(exc);
              finally
                   try{
                   if(networkIn!=null) networkIn.close();
                   if(sockOut!=null) sockOut.close();}
                   catch(IOException exc){ }
                   EchoServer.java
    //EchoServer.java
    import java.io.*;
    import java.net.*;
    class EchoServer
         public static void main(String args[])
              int portNo=6666;
              ServerSocket serverSock=null;
              try
                   serverSock=new ServerSocket(portNo);
                   System.out.println("Echo Server Started\n\n");
                   while(true)
                        Socket clientSock=serverSock.accept();
                        new Thread(new EchoServerThread(clientSock)).start();
              catch(IOException exc)
                   System.err.println(exc);
         EchoServerThread.java
    //EchoServerThread.java
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class EchoServerThread implements Runnable
         public Socket clientSock;
         EchoServerThread(Socket sock)
              clientSock=sock;
         public void run()
              System.out.println("\nAccepted Connection from a Client");
              try{
              BufferedReader in=new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
              BufferedReader userIn=new BufferedReader(new InputStreamReader(System.in));
              PrintWriter out= new PrintWriter(clientSock.getOutputStream());
                        /*In sockIn=new In(clientSock);
              Out sockOut=new Out(clientSock);*/
              String str;
              while((str=in.readLine())!=null)
                   out.println(str);
                   out.flush();
              System.out.println("Closing Connection from a Client");
              out.close();
              in.close();
              catch(IOException exc)
                   System.err.println(exc);
         

    Sorry everyone but I'd been giving a wong IP address thinking it's my own. The problem's solved.
    Thanks for the response Peter.

  • Problem with Socket Client - Intermittent Truncated Response in AIX

    {color:#0000ff}Hi guru
    I have written on Socket Client method below to send request byte[] to Host and receive response byte[] from Host.
    For this particular response, I'm expecting Host to return me byte[] with length 2274.
    My problem is intermittently I received truncated message byte[] from Host with length only 1392. Sometimes I received full 2274 message, sometimes I received 1392 length. I tested in continual of 10 times by sending the same request to host, intermittently received truncated response message.
    My real problem is that this only happened in {color:#ff0000}AIX {color}machine. With the same class, I tested on {color:#ff0000}Windows {color}platform and i received full response message byte[] with 2274 lenght always. Therefore, im counting out the possibilities that Host might send me truncated message.
    Can anyone pls help to tell me how should I proceed to troubleshoot this problem in AIX? Is possible for me to trace what coming in?
    {color}
    public byte[] sendToHost(byte[] requestMessage, String requestId, String localTxnCode) throws Exception {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    long startTime = 0;
    long elapsed = 0;
    try {
    LogManager.log(LogManager.DEBUG, Constants.DEFAULT_LOGGER_NAME, requestId, "[" + localTxnCode + "] To connect and send message to Host hostAddr=[" + hostAddr + "], hostPort=[" + hostPort
    + "]");
    startTime = System.currentTimeMillis();
    hostSocket = new Socket(InetAddress.getByName(hostAddr), hostPort);
    hostSocket.setSoTimeout(timeOut);
    byte responseData[] = new byte[4096];
    bis = new BufferedInputStream(hostSocket.getInputStream());
    bos = new BufferedOutputStream(hostSocket.getOutputStream());
    bos.write(requestMessage);
    bos.flush();
    int length = bis.read(responseData);
    elapsed = System.currentTimeMillis() - startTime;
    ARBAdapterUtil.log(LogManager.DEBUG, Constants.DEFAULT_LOGGER_NAME, requestId, "[" + localTxnCode + "] Received message from Host length=[" + length + "]");
    // The response byte must not be 4096 everytime
    byte[] returnByte = new byte[length];
    for (int i = 0; i < length; i++) {
    returnByte[i] = responseData;
    return returnByte;
    } catch (BindException b) {
    elapsed = System.currentTimeMillis() - startTime;
    throw new SocketException("Socket Exception: BindException IP=" + hostAddr + " PORT=" + hostPort + " Error type=" + b.getClass().getName() + " Error message=" + b.getMessage());
    } catch (ConnectException c) {
    elapsed = System.currentTimeMillis() - startTime;
    throw new SocketException("Socket Exception: ConnectException IP=" + hostAddr + " PORT=" + hostPort + " Error type=" + c.getClass().getName() + " Error message=" + c.getMessage());
    } catch (NoRouteToHostException nrth) {
    elapsed = System.currentTimeMillis() - startTime;
    throw new SocketException("Socket Exception: NoRouteToHostException IP=" + hostAddr + " PORT=" + hostPort + " Error type=" + nrth.getClass().getName() + " Error message="+ nrth.getMessage());
    } catch (SocketTimeoutException se) {
    elapsed = System.currentTimeMillis() - startTime;
    throw new SocketTimeoutException("Socket Exception: SocketTimeoutException IP=" + hostAddr + " PORT=" + hostPort + " Error type=" + se.getClass().getName() + " Error message=" + se.getMessage());
    } catch (SocketException s) {
    elapsed = System.currentTimeMillis() - startTime;
    throw new SocketException("Socket Exception: SocketException IP=" + hostAddr + " PORT=" + hostPort + " Error type=" + s.getClass().getName() + " Error message=" + s.getMessage());
    } catch (Exception e) {
    elapsed = System.currentTimeMillis() - startTime;
    throw new Exception("Unknown Exception: Exception IP=" + hostAddr + " PORT=" + hostPort + "Error type=" + e.getClass().getName() + " Error message=" + e.getMessage());
    } finally {
    try {
    ARBAdapterUtil.log(LogManager.INFO, Constants.DEFAULT_LOGGER_NAME, requestId, "ARBConnection.sendToHost() [" + localTxnCode + "] Time Elapsed via Socket in millisecond = [" + elapsed + "]");
    if (bis != null) {
    bis.close();
    bis = null;
    if (bos != null) {
    bos.close();
    bos = null;
    } catch (Exception e) {
    LogManager.log(LogManager.ERROR, Constants.DEFAULT_LOGGER_NAME, requestId, "ARBConnection.sendToHost() [" + localTxnCode + "] Exception during closing BufferedInputStream and BufferedOutputStream");

    I tried to use DataInputStream.readFully(byte[]). However, I could not retrieve a single byte from Host. It won't return until it fills the buffer, or EOS occurs. Isn't that what you wanted?
    You need to believe it here. Either the sending application or Java or the sending TCP stack or the intervening routers or the receiving TCP stack or Java or the receiver can break up the transmission into 1 byte reads and there is nothing you can do about it at the receiver except what I said. BufferedInputStream will mask the effect to some extent but you still have to code under that assumption. You don't have any choice about this.

  • Problem with socket connection in midp 2.0

    hello everyone.
    I'm new one in j2me and I am learning socket connection in j2me. I'm using basic socket,datagram example wich is come with sun java wireless toolkit 2.5. for it i wrote small socket server program on c# and tested it example on my pc and its working fine. also socket server from another computer via internet working fine. But when i instal this socket example into my phone on nokia n78 (Also on nokia 5800) it's not working didn't connect to socket server.. On phone I'm using wi-fi internet. Can anybody help me with this problem? I hear it's need to modify manifest file and set appreciate pressions like this
    MIDlet-Permissions: javax.microedition.io.Connector.socket,javax.microedition.io.Connector.file.write,javax.microedition.io.Connector.ssl,javax.microedition.io.Connector.file.read,javax.microedition.io.Connector.http,javax.microedition.io.Connector.https
    is it true?
    can anybody suggest me how can i solve this problem?
    where can I read full information about socket connection specifiecs in j2me?
    Thanks.

    Maybe this can be helpful:
    [http://download-llnw.oracle.com/javame/config/cldc/ref-impl/midp2.0/jsr118/index.html]
    you can check there the Datagram interface anda DatagramConnection interface and learn a little about that.
    If the client example runs fine in the wireless toolkit emulator, it should run the same way in your phone; i suggest to try to catch some exception that maybe is hapenning and display it on a Alert screen, this in the phone.

  • Problem with socket programming-connecting to port 13

    Hi, I am learning JAVA, and we are on the subject of sockets. I am trying to make this program to connect to port 13, get the time, and print it to the console. This is my code:
    import java.io.*;
    import java.net.*;
    public class temp {
         public static final int PORT = 13;
         public static void main(String[] args) {
              Socket s = null;
              String line = null;
              try {
                   s = new Socket("localhost", PORT);
                   DataInputStream sin = new DataInputStream(s.getInputStream());
                   line = sin.readLine();
                   if (line != null) System.out.println(line);
              catch (IOException e) {System.err.println("!" + e);}
              finally {
                   try { if (s != null) s.close(); }
                   catch (IOException e2) {}
    And this is the output:
    !java.net.ConnectException: Connection refused: connect
    What should I do. I found that the problem is with the server I am connecting to and I tried connecting to dif. computers, or to stuff online, and nothing works.
    Any suggestions for me?
    Forgot: I tried this on both a windows XP and Vista
    Edited by: xpatrickerx on Mar 23, 2008 8:12 PM
    Tampering with it, I find that the error occurs on the following line:
    s = new Socket("localhost", PORT);
    Edited by: xpatrickerx on Mar 23, 2008 8:13 PM

    So I finally found how to use printStackTrace and here is what it gives when:
    1) I use my own computer:
    java.net.ConnectException: Connection refused: connect
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(Unknown Source)
         at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
         at java.net.PlainSocketImpl.connect(Unknown Source)
         at java.net.SocksSocketImpl.connect(Unknown Source)
         at java.net.Socket.connect(Unknown Source)
         at java.net.Socket.connect(Unknown Source)
         at java.net.Socket.<init>(Unknown Source)
         at java.net.Socket.<init>(Unknown Source)
         at temp.main(temp.java:11)
    2) I use something else:
    java.net.ConnectException: Connection timed out: connect
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(Unknown Source)
         at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
         at java.net.PlainSocketImpl.connect(Unknown Source)
         at java.net.SocksSocketImpl.connect(Unknown Source)
         at java.net.Socket.connect(Unknown Source)
         at java.net.Socket.connect(Unknown Source)
         at java.net.Socket.<init>(Unknown Source)
         at java.net.Socket.<init>(Unknown Source)
         at temp.main(temp.java:11)
    Again, thanks

  • Problem with socket security

    Hi,
    I'm trying to make socket connection from within air application, but no way. I'm browsing google for almost 2 days, follow all possible solutions, but avidently I dont understund somthing cause I'm not able to do anything.
    Every time sandbox security violation.....  I need make some simple socket data exchange between my air, and OS. I do not have any web server and no any other kind of network ability. I write down stupid socket server, which is waiting for policy request, and for my other requests (it function 100%, tested with Telnet, so no way to have problem on my socket server side).
    The strange thing is that my application do not produce any request for socket policy file, neither at 843 port (for default), neither at my custom location with namual
    Security.loadPolicyFile("xmlsocket://ip:port"); call
    This is my primitive code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical">
        <mx:Script>
            <![CDATA[
                private var s:XMLSocket = null;
                private function test():void{
                    Security.loadPolicyFile("xmlsocket://127.0.0.1:25013");
                    if(!s){
                        s = new XMLSocket();
                        s.addEventListener(DataEvent.DATA, onData);
                        s.addEventListener(Event.ACTIVATE, onActivate);
                        s.addEventListener(Event.CONNECT, onConnect);
                        s.addEventListener(Event.DEACTIVATE, onDeactivate);
                        s.addEventListener(IOErrorEvent.IO_ERROR, onError);
                        s.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurity);
                    s.connect("127.0.0.1", 25013);
                private function onActivate(e:Event):void{
                    debug.text += "Activated\r";
                private function onConnect(e:Event):void{
                    debug.text += "Connected\r";
                    var o:XML = <request cmd="10"/>;
                    s.send(o);
                private function onDeactivate(e:Event):void{
                    debug.text += "Deactivated\r";
                private function onError(e:IOErrorEvent):void{
                    debug.text += e.text + "\r";
                private function onSecurity(e:SecurityErrorEvent):void{
                    debug.text += e.text + "\r";
                private function onData(e:DataEvent):void{
                    debug.text += e.data;
                    s.close();
            ]]>
        </mx:Script>
        <mx:Button label="Test" click="test()"/>
        <mx:TextArea id="debug" width="100%" height="100%"/>
    </mx:WindowedApplication>
    Any help will be apresciated.
    Ladislav.

    Hi,
    It pass some time but if i remember well, my problem was that i did
    not terminate stream output form my server vs air application, and it
    returns this security error.
    When I send  '\0' at the end of my message it work correctly. Yes the
    server was my own written socket server (c++ using boost libraries).
    Laco.
    Sorry late response I'm on hollydays
    Staney G ha scritto:
    So, how did you walk around the problem?  Did you have a control on how server responds?
    My test case failed similarly.  However, the target server is a public web service.
    Will appreciate your answers!
    >

  • Problem with socket communications

    I am trying to put together a client server socket communication pair.
    I have one application that runs in the background acting as a server and another that can be started and stopped that acts as a client.
    I can start the server and create a server socket with no problem.
    I can start the client and it connects to the server.
    The server acknowledges the connection and appears to go into a blocking state waiting for the client to send another message.
    The server blocks at the line
    parent.logit("Waiting for message from EVR..... ");
    The problem is that when the client sends another message, the server doesn't hear it.
    I am not sure if the problem is with the client or server communication code.
    If anyone out there is a socket communication guru, I would appreciate it if you could tell me what I am doing wrong.
    Thanks
    Server code:
    import java.io.*;
    import java.net.*;
    public class EVRServer
        extends Thread
      EVRDataLoader parent = null;
      ServerSocket serverSock = null;
      Socket clientSock = null;
      BufferedReader reader = null;
      BufferedWriter writer = null;
      int evrPort = 0;
      int retryLimit = 10;
      int retryCount = 0;
      boolean alive = false;
      boolean killSocket = false;
      boolean evrConnected = false;
      boolean retry = true;
      EVRListener evrListener = null;
    //=============================================================================
    // Full constructor
    //=============================================================================
       * Full constructor.
       * @param dl DataLoader - Parent application
       * @param port int Socket port
      public EVRServer(EVRDataLoader dl, int port)
        parent = dl;
        evrPort = port;
    //=============================================================================
    //  Run method - Main thread executed by start() method
    //=============================================================================
       * Main thread executed by start() method
      public void run()
        while (retry)
          if (retryCount > retryLimit)
            retry = false;
          parent.logit("Retry count = " + retryCount);
          // Create new server socket connection
          if (serverSock == null)
            try
              serverSock = new ServerSocket(evrPort);
              parent.logit("Created Server Socket for EVR on port " + evrPort);
              alive = true;
              killSocket = false;
              evrConnected = false;
            catch (Exception e)
              parent.logit(
                  "ERROR - Could not create Server socket connection for EVR: " +
                  e.toString());
              killSocket = true;
              alive = false;
          // Create new client socket connection
          if (clientSock == null)
            try
              parent.logit("Waiting for EVR to connect");
              clientSock = null;
              clientSock = serverSock.accept();
              retryCount = 0;
              evrConnected = true;
              killSocket = false;
              parent.logit("EVR connected on server Socket Port " + evrPort);
            catch (Exception e)
              parent.logit("ERROR - Error accepting EVR connection: " + e.toString());
              killSocket = true;
            try
              reader = new BufferedReader(new InputStreamReader(
                  clientSock.getInputStream()));
              writer = new BufferedWriter(new OutputStreamWriter(
                  clientSock.getOutputStream()));
              parent.logit( "Created reader "+reader);
              parent.logit( "Created writer "+writer);
            catch (Exception e)
              parent.logit(
                  "ERROR - creating reader or writer to EVR: " + e.toString());
              killSocket = true;
          int nullCount = 0;
          while (killSocket == false)
            try
              parent.logit("Waiting for message from EVR..... ");
    //          sendMessage("Data Controller connected on port " + evrPort);
              String s = reader.readLine();
              parent.logit("EVR - Received message: " + s);
              if (s != null)
                parent.processEvrMessage( s);
              else
                sleep(1000);
                nullCount++;
                if (nullCount > 10)
                  parent.logit("Exceeded retry limit: ");
                  killSocket = true;
            catch (Exception ex)
              parent.logit("Error Reading from EVR: " + ex.toString());
              killSocket = true;
          parent.logit( "After while loop");
          evrConnected = false;
          try
            retryCount++;
            parent.logit("Closing EVR connection. ");
            reader.close();
            writer.close();
            clientSock.close();
            writer = null;
            reader = null;
            clientSock = null;
            try
              sleep(1000);
            catch (Exception ee)
              parent.logit("Error after sleep " + ee.toString());
          catch (Exception e)
            parent.logit("Error closing EVR server socket");
    //=============================================================================
    // Call this method to kill the client socket connection.
    //=============================================================================
       * Call this method to kill the client socket connection.
      public void killConnection()
        killSocket = true;
    //=============================================================================
    // Return RTM connected state
    //=============================================================================
       * Return RTM connected state
       * @return boolean - Returns true if RTM is connected to server, false if not.
      public boolean isRtmConnected()
        return evrConnected;
    //=============================================================================
    // Returns state of server socket.
    //=============================================================================
       * Returns state of server socket.
       * @return boolean - Returns true if server socket is enabled, false if not.
      public boolean isServerSocketAlive()
        return alive;
    //=============================================================================
    // Send a message to the client socket.
    //=============================================================================
         * Send a message to the client socket.
         * @param msg String - Message to send.
         * @return boolean - Returns true if message sent OK, false if not.
      public boolean sendMessage(String msg)
        parent.logit(" In EVR Server - Send Message - got message: " + msg);
        if (evrConnected)
          try
            parent.logit("Sending message to EVR: " + msg);
            writer.write(msg + "\n");
            writer.flush();
            return true;
          catch (Exception e)
            parent.logit("ERROR - Error sending message to EVR: " + e.toString());
            return false;
        else
          parent.logit("EVR not connected, cannot send message: " + msg);
          return false;
    }Client code:
    package evrsimulator;
    import java.net.*;
    import java.io.*;
    class PortConnector
          extends Thread
       ServerSocket serverSock = null;
       boolean isIP = false;
       InetAddress addr = null;
       Frame1 parent = null;
       byte[] rawIP;
        //   String initialMsg = "";
       public PortConnector( Frame1 f )
         parent = f;
       // This method is called when the thread runs
       public void run()
          if ( parent.hostName.indexOf( "." ) > 0 )
             isIP = true;
             byte[] rawIP = parent.getRawIP( parent.hostName );
          try
             System.out.println( "Connecting to host " +
                                            parent.hostName + " on port " +
                                            parent.socketPort );
             if ( isIP )
                addr = InetAddress.getByAddress( rawIP );
             else
                addr = InetAddress.getByName( parent.hostName );
             System.out.println( "Inet address = " + addr );
             SocketAddress sockaddr =
                   new InetSocketAddress( addr, parent.socketPort );
             // Create an unbound socket
             parent.client = new Socket();
             // This method will block no more than timeoutMs.
             // If the timeout occurs, SocketTimeoutException is thrown.
             parent.client.connect( sockaddr, parent.socketTimeOut );
             parent.socketOut =
                   new BufferedWriter( new OutputStreamWriter(
                   parent.client.getOutputStream() ) );
             parent.socketIn = new BufferedReader( new InputStreamReader(
                   parent.client.getInputStream() ) );
             parent.localName = parent.localName +
                   parent.client;
             System.out.println( "Parent socketOut = "+parent.socketOut);
             System.out.println( "Parent socketIn = "+parent.socketIn);
          catch ( UnknownHostException uhe )
             System.out.println( "Unknown Host - " + uhe.getMessage() );
          catch ( SocketTimeoutException ste )
             System.out.println( "Socket time out - " + ste.getMessage());
          catch ( IOException ioe )
             System.out.println( "IO exception - " + ioe.getMessage() );
          // Listen on socket for message from host - thread should block.
          parent.portConnected = true;
          while ( parent.portConnected )
             try
                String msg = parent.socketIn.readLine();
                System.out.println( "Message from Host: " + msg );
                System.out.println( "Message from Host: |" + msg + "|" );
                if( msg.length() > 2)parent.processMessage( msg );
             catch ( IOException ioe )
                System.out.println( "Exception creating server socket." );
          try
             System.out.println(
                   "PortConnection - Closing socket and IO connections" );
             parent.socketIn.close();
             parent.socketOut.close();
             parent.client.close();
             parent.clockRunning = false;
             if( parent.heartBeating) heartBeat.interrupt();
          catch ( IOException ioex )
             System.out.println( "Exception closing socket." );
    }

    Your first problem is that you keep closing and recreating the ServerSocket. Do this once only in the lifetime of the server.
    This is such a basic error that I haven't read the rest of the code. Before you go any further I suggest you read the Custom Networking trail of the Java Tutorial.

  • Problem with socket - Client in C and Server in Java

    Hi,
    I am building a Java based TCP server socket class in Windows machine. The client is written in C running in Linux.
    The client sends data in specified C struct: Eg.
    {noformat}struct person {
        int   age;
        float weight;
        int height;
      } I am having problem reading it in Java Server. I am using DataInputStream to read byte and trying to decode it in age, float etc. the problem is I can read first two but I cannot properly decode the 'height'.
    My question is it possible to directly cast the input stream in corresponding Java object? I guess not but would like to know your ideas.
    Is it a good idea to send the struct instead of string?
    regards,
    rnv

    You are perpetrating mistake #1 here. Don't try to send C structs over the wire. The format is dependent on the hardware, the operating system, the compiler, the compiler version, compiler bugs, the #pragmas, and the compiler options in effect. Too many variables. What you should be doing is writing the primitive types to the network, in network byte order, and reading them inJava with the appropriate methods of DataInputStream.

  • Problem with socket in java and c++

    I am connecting to a server developed in java that use sys/socket.h, this server use DataInputStream
    class and readUTF so:
    in = new DataInputStream(socket.getInputStream());
    inputString = in.readUTF()
    My application in C++ it use winsock2.h and I utilize the method "send" in order to send the plots to the server
    java got hold of:
    #define MAXLONGITUD 10000
    char     bufEnviados[MAXLONGITUD + 1];
    bufEnviados[0] = (0xff & (longitud >> 8));
    bufEnviados[1] = (0xff & longitud);
    send(sock, bufEnviados,strlen(bufEnviados), 0 );
    I send the two first characters with UTF format so that the server in java could recognize them.
    The application operated correctly it until received an old plot of 6.236 characters later
    from which it close the connection with the socket and it fall my application!
    I have carried out several tests and I don't succeed in sending more than those 6.236 characters, however it achievement receibing whatever quantity of characters without problems!
    Could somebody help me to resolve this problem? I am attempting of everything and I don't achieve it!
    Ahead of time thank you!

    alfaximena wrote:
    #define MAXLONGITUD 10000
    char     bufEnviados[MAXLONGITUD + 1];
    bufEnviados[0] = (0xff & (longitud >> 8));
    bufEnviados[1] = (0xff & longitud);
    send(sock, bufEnviados,strlen(bufEnviados), 0 );
    Are you sending characters or binary data? You mention "plot" which sounds like binary data. You cannot send binary data via character encoding. Characters in java are not just bits, they are mapped values. If you encode it with something like base64 then that should be ok.
    I can only suppose that your testing was with data sets greater than 255, because strlen() would not have worked otherwise.
    Since you have the size then use it rather than using strlen().
    I send the two first characters with UTF format so that the server in java could recognize them.
    The application operated correctly it until received an old plot of 6.236 characters later
    from which it close the connection with the socket and it fall my application!
    There is nothing special about that particular number. So I would guess that the data in that set is the problem. Probably because you are in fact sending binary data. If, for example, a byte with a value of zero showed up in the sequence then strlen() would return an incorrect value compared to the size that you told java you are sending.

  • Problem with Socket and dynamic IP

    The problem I have is the following: My domain has a dynamic IP, so after the IP changes the s.accept() does not work any more!
    try // Point 1 *)
    ServerSocket s = new ServerSocket(portNumber);
    for(;;)
    Socket incoming = s.accept(); // does not work after IP changes
    new ThreadedEchoHandler(incoming, i).start();
    So I have to detect that the IP has changed and have to start again at Point 1
    How can I do this?
    thx walter

    Something is vary wrong with your network software if your getting an error on that.
    When you start your computer connected to the network, a DHCP (in your case) Server sends your NIC a dynamic IP address, we call this process "binding". When the client computer connects it also is given an IP address to bind to. You can't connect to anything, or in your case create a ServerSocket, if you dont even have an IP. So your Server has an IP address, and so does the client. You should not be getting any errors unless the client/server network is using two different protocols. You can't run an IPX/SPX network and a TCP/IP network together without a Bridge.
    That does not seem to be your problem. I believe, then, that the problem is that your ThreadedEchoHandler is holding the CPU. Instead of having a client connect (s.accept()) outside of that thread. Have the thread be created by using the arugment of the ServerSocket instead and no the Socket object created.
    new ThreadedEchoHandler(ServerSocket ss);
    Then let it do it's thing. Also, you will need to call it's start() method to actually run the thread as a thread. Otherwise it runs as a simple class.

Maybe you are looking for

  • How to fix calendar date inconsistency

    Hello, I have a problem with closing material period due to inconsistency with actual calendar date. Last closed period in material master of specific cc is 07.2009.(It is test system with IDES database). How to close remaining periods to 01.2012. I

  • No sound on my videos

    I downloaded some videos and tv shows from Itunes and they don't have any sound. Other things have sound like my music, its just my tv shows and videos that have no sound.

  • Processed TRs to be deleted from LB10(display TRs list for a storage type)

    Dear all Is it possible to delete already processed transfer requirements for a storage type in Transaction LB10? Please guide me

  • OBIEE Admin tool Crashing

    We have two OBIEE environment running with the 11.1.1.6 version of OBIEE. We have developed a .rpd in one of the environment and able to run it in that envioronment. Using the Admin tool we have taken a copy of that .rpd file to an another enviornmen

  • Source System Issue

    Hi Gurus, I am getting "No matching FM area found" and "errors in the source system" when I try to load data thru an InfoPackage into PSA in BI7.0. This is newly installed BW DEV system for demo purposes. I have checked that the latest SP13 are insta