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]

Similar Messages

  • Problem with oracle.jbo.domain.Date

    Hi there,
    I've a problem with oracle.jbo.domain.Date,
    I'm doing this code (this part of code is used in my Session Attribute Listener):
    * This method is used to add the session id in the database, whenever user login
    public void attributeAdded(HttpSessionBindingEvent hsbe){
    if(!hsbe.getName().equals("user")){
    return;
    AmLogin am = (AmLogin)Configuration.createRootApplicationModule(
    "com.ahm.pdt001.am.AmLogin",
    "AmLoginLocal");
    try{
    hsbe.getSession().setAttribute("login", new Date(new Timestamp(
    System.currentTimeMillis())));
    am.createLogin(hsbe.getValue().toString(), hsbe.getSession().
    getAttribute("login").toString());
    } catch(Exception e){
    e.printStackTrace();
    System.out.println("Error insert data user: " + hsbe.getValue());
    } finally{
    Configuration.releaseRootApplicationModule(am, true);
    Everything is running well in Jdev 10.1.3 (I'm using ADF Faces technology), and I'm trying to deploy it on OC4J 10.1.2 and it works. But it raised an error when this part of code is runned.
    --------------caused and error------------------------
    hsbe.getSession().setAttribute("login", new Date(new Timestamp(
    System.currentTimeMillis())));
    And this is an error:
    javax.faces.FacesException: #{pdt001.loginAction}: javax.faces.el.EvaluationException: java.lang.NoSuchMethodError: oracle.jbo.domain.Date.<init>(Ljava/sql/Timestamp;)V     at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:78)     at oracle.adf.view.faces.component.UIXCommand.broadcast(UIXCommand.java:211)     at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:267)     at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:381)     at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:75)     at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:200)     at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:90)     at javax.faces.webapp.FacesServlet.service(FacesServlet.java:197)     at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.0.0)].server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)     at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:332)     at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.0.0)].server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:16)     at oracle.adfinternal.view.faces.webapp.AdfFacesFilterImpl._invokeDoFilter(AdfFacesFilterImpl.java:367)     at oracle.adfinternal.view.faces.webapp.AdfFacesFilterImpl._doFilterImpl(AdfFacesFilterImpl.java:336)     at oracle.adfinternal.view.faces.webapp.AdfFacesFilterImpl.doFilter(AdfFacesFilterImpl.java:196)     at oracle.adf.view.faces.webapp.AdfFacesFilter.doFilter(AdfFacesFilter.java:87)     at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.0.0)].server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:20)     at com.ahm.filter.AhmFilterSession.doFilter(AhmFilterSession.java:45)     at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.0.0)].server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:645)     at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.0.0)].server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:322)     at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.0.0)].server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:790)     at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.0.0)].server.http.HttpRequestHandler.run(HttpRequestHandler.java:270)     at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.0.0)].server.http.HttpRequestHandler.run(HttpRequestHandler.java:112)     at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.0.0)].util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:186)     at java.lang.Thread.run(Thread.java:534)Caused by: javax.faces.el.EvaluationException: java.lang.NoSuchMethodError: oracle.jbo.domain.Date.<init>(Ljava/sql/Timestamp;)V     at com.sun.faces.el.MethodBindingImpl.invoke(MethodBindingImpl.java:130)     at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:72)     ... 23 moreCaused by: java.lang.NoSuchMethodError: oracle.jbo.domain.Date.<init>(Ljava/sql/Timestamp;)V     at com.ahm.pdt001.listener.Pdt001AttributeSessionListener.attributeAdded(Pdt001AttributeSessionListener.java:27)     at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.0.0)].server.http.EvermindHttpSession.setAttribute(EvermindHttpSession.java:128)     at com.ahm.pdt001.bean.Pdt001Bean.loginAction(Pdt001Bean.java:61)     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)     at java.lang.reflect.Method.invoke(Method.java:324)     at com.sun.faces.el.MethodBindingImpl.invoke(MethodBindingImpl.java:126)
    Does anybody have the same problem like this? I've used the same method in my previous project to create oracle.jbo.domain.Date with current time using java.sql.Timestamp, but I don't know why this error happened.
    Thx,
    Andre

    Re: oracle jbo.domain.Date issues in 10.1.3
    Sascha

  • Problem with socket and Flash

    I have a chat application where the client is written in Flash 9 and it connects an XMLSocket to my java server.
    Those that know Flash 9 know that it first makes a policy file request and all you have to do is provide a small chunk of xml stating the desired port and domain.
    To get a better understanding I adding some thread tracking to the server app. Now when I run the following:
    String policy_response = "<?xml version=\"1.0\"?><cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"6000\" secure=\"false\" /></cross-domain-policy>"+ "\0";
    ErrorBroker.addError("name: " + this.currentThread().getName());
    String mes = "";
    if(cs.incoming.ready())
         mes = cs.readln();
         ErrorBroker.addError( this.currentThread().getName()+ " ready: " + mes);
    if(mes.equals("<policy-file-request/>" + "\0"))
         ErrorBroker.addError( this.currentThread().getName()+ " policy hit");
         cs.send(policy_response);
    counter++;
    ErrorBroker.addError( this.currentThread().getName()+" counter: " + counter);and the results I get are the following:
    name: Thread-34
    Thread-34 in ready: <policy-file-request/>
    Thread-34 policy hit
    Thread-34 counter: 1
    Thread-34 after read2: <policy-file-request/>
    END OF processClient()
      Closing socketThere is no second connection though there should be. On the flash end I get nothing..no message stating a connection made or lost.
    Now if I have the server as such:
    ErrorBroker.addError("name: " + this.currentThread().getName());     
    String mes = "";
    /* ---- policy response sent BEFORE readLine() ---- */
    cs.send(policy_response);
    if(cs.incoming.ready())
         mes = cs.readln();
         ErrorBroker.addError( this.currentThread().getName()+ " in ready: " + mes);
    if(mes.equals("<policy-file-request/>" + "\0"))
         ErrorBroker.addError( this.currentThread().getName()+ " policy hit");
    counter++;
    ErrorBroker.addError( this.currentThread().getName()+" counter: " + counter);The one difference being that the policy reply happens before any read.
    I get these results:
    name: Thread-34
    Thread-34 in ready: <policy-file-request/>
    name: Thread-35
    Thread-34 policy hit
    Thread-35 counter: 1
    Thread-34 counter: 2
    Thread-35 after read2:
    Thread-34 after read2: <policy-file-request/>
    io error1: java.lang.StringIndexOutOfBoundsException:String index out of range: 0
    END OF processClient()
    END OF processClient()
      Closing socket
      Closing socketDoes this make sense to anyone? How is it that if I do a readLine before sending the policy request file that nothing happens but I send after a readLine the second socket shows up.
    Any help is GREATLY appreciated.

    The second case does appear to be a threading issue.....but what bothers me the most is why I get nothing from flash when I readLine first. This doesn't seem to be an issue with anyone else and I've seen many examples (though almost all were written in PHP) that are exactly the same. Read first...look for the policy request...then reply accordingly.
    This is a small chat application running on Tomcat 5.5.
    It worked well back when I ran it with Flash 8 but since I upgraded to Flash 9 (had to...no other way around) I now have to deal with this policy issue (apparently it pissed off quite a few developers).

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

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

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

Maybe you are looking for