Server + Client in singular class - problems

hi all. I'm currently developing a single class file which will (in order) do the following:
1. (act as a server) recieve a string.
2. (act as a client) pass the string on to another class.
3. (act as a server again) recieve the modified string back.
so far I can sucessfully recieve the first string and pass it onwards to the other class but I don't appear to be recieve anything back from it... my application just sits there, waiting. i know the class that should be returning the string is correct so i think i have a problem with my socket connections when trying to act as a server for the 2nd time.
here is some of my prototype code:
ServerSocket serverSocket = new ServerSocket(3000);
Socket socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String text = reader.readLine();
// First string recieved.
Socket clientSocket = new Socket("localhost", 3001);
PrintWriter writer = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
writer.println(text);
writer.flush();
// First string passed on to other client.
System.out.println("waiting to recieve translation");
// nothing happens from here onwards
socket = serverSocket.accept();
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String text2 = reader.readLine();
System.out.println(text2);
I'm think I'm having trouble re-using the original server socket to listen for a second connection. I've tried closing the socket after the first connection and re-creating it but that doesn't work either and just gives me a Error with serverjava.net.BindException: Address already in use: JVM_Bind.
thoughts appreciated. thanks!

If the "thing" that is connecting to your ServerSocket never closes, you should NOT make another accept() call.
Its either:
server accept()
"thing" connects to server
"thing" sends a string
server receives the string
"thing" closes
server close
... and this loop goes on and on ...
-OR-
server accept()
"thing" connects to server
"thing" sends a string
server receives the string
"thing" sends another string
server receives the other string
... sends/receives on and on ...
eventually "thing" and server closes

Similar Messages

  • Coherence Client without POF classes problem

    I have a special Coherence client node that will be performing cache invalidation tasks only. namedCache.keySet().remove( removeKey ); I will never actually send or deserialize the objects to this node.
    This node has no need to have to have the classes related to POF on it, and I really never want to have to update/perform maintenance on this node when updates are made to the classes on the actual cache nodes.
    Is there any way I can setup/configure this node so that in its coherence-cache-config, I am not required to provide the serializer config or not have to provide the classes behind the serializer?
    When I attempt to do this, Coherence complains that this node's is configured to use serializer com.tangosol.io.pof.ConfigurablePofContext which appears to be different from the serializer used by other members.
    If I set the serializer, it then complains that the ClassNotFound if I dont place all the classes on this special invalidator node.
    Please help!!! I dont want this special client to have to have all the POF details and classes!!!! He will never need it.
    Thanks,
    J
    Edited by: user12017793 on Sep 11, 2011 9:27 PM

    I'm not sure it is that messy.
    1. The custom client side serializer
    package com.gridman.test;
    import com.tangosol.io.ReadBuffer;
    import com.tangosol.io.WriteBuffer;
    import com.tangosol.io.pof.ConfigurablePofContext;
    import com.tangosol.io.pof.PofBufferReader;
    import com.tangosol.io.pof.PofBufferWriter;
    import com.tangosol.io.pof.PofContext;
    import java.io.IOException;
    public class PassThroughPofContext extends ConfigurablePofContext {
        public PassThroughPofContext(String sLocator) {
            super(sLocator);
        @Override
        public void serialize(WriteBuffer.BufferOutput out, Object o) throws IOException {
            try {
                if (o instanceof PassThrough) {
                    PassThrough passThrough = (PassThrough)o;
                    out.writePackedInt(passThrough.getType());
                    out.writeBuffer(passThrough.getValue());
                } else {
                    PofBufferWriter writer = new PofBufferWriter(out, this);
                    writer.writeObject(-1, o);
            } catch (RuntimeException e) {
                throw new IOException(e.getMessage(), e);
        @Override
        public Object deserialize(ReadBuffer.BufferInput in) throws IOException {
            try {
                Reader reader = new Reader(in, this);
                return reader.readObject(-1);
            } catch (RuntimeException e) {
                throw new IOException(e.getMessage(), e);
        @Override
        public int getUserTypeIdentifier(Object o) {
            int id;
            if (o instanceof PassThrough) {
                id = ((PassThrough)o).getType();
            } else {
                id = super.getUserTypeIdentifier(o);
            return id;
        private boolean isUserType(int type) {
            ensureInitialized();
            Class[] types = this.getPofConfig().m_aClzByTypeId;
            return types.length > type && types[type] != null;
        private class Reader extends PofBufferReader {
            private Reader(ReadBuffer.BufferInput in, PofContext ctx) {
                super(in, ctx);
            @Override
            protected Object readAsObject(int nType) throws IOException {
                Object value;
                if (((PassThroughPofContext)this.m_ctx).isUserType(nType)) {
                    value = super.readAsObject(nType);
                } else {
                    value = new PassThrough(nType, this.m_in);
                return value;
    }2. The class that will be used to hold anything that the serializer does not know how to handle
    package com.gridman.test;
    import com.tangosol.io.ReadBuffer;
    import java.io.IOException;
    public class PassThrough {
        private int type;
        private ReadBuffer value;
        public PassThrough(int type, ReadBuffer.BufferInput in) throws IOException {
            this.type = type;
            this.value = in.readBuffer(in.available());
        public int getType() {
            return type;
        public ReadBuffer getValue() {
            return value;
    }3. The client cache config
    <cache-config>
        <caching-scheme-mapping>
            <cache-mapping>
                <cache-name>*</cache-name>
                <scheme-name>proxy</scheme-name>
            </cache-mapping>
        </caching-scheme-mapping>
        <caching-schemes>  
            <remote-cache-scheme>
                <scheme-name>proxy</scheme-name>
                <service-name>extend-service</service-name>
                <initiator-config>
                    <tcp-initiator>
                        <remote-addresses>
                            <socket-address>
                                <address>... put host name here ...</address>
                                <port>10000</port>
                            </socket-address>
                        </remote-addresses>
                    </tcp-initiator>
                    <serializer>
                        <instance>
                            <class-name>com.gridman.test.PassThroughPofContext</class-name>
                            <init-params>
                                <init-param>
                                    <param-type>String</param-type>
                                    <param-value system-property="tangosol.pof.config">coherence-pof-config.xml</param-value>
                                </init-param>
                            </init-params>
                        </instance>
                    </serializer>
                </initiator-config>
            </remote-cache-scheme>
        </caching-schemes>
    </cache-config>The above code and config is all you need. Everything below here is to test it.
    To test it we just convert a class to Binary and back again using the server and client serializers E.G.
    A simple POF class to test with - this would only be on the server side
    package com.gridman.test;
    import com.tangosol.io.pof.PofReader;
    import com.tangosol.io.pof.PofWriter;
    import com.tangosol.io.pof.PortableObject;
    import java.io.IOException;
    public class TestPortableObject implements PortableObject {
        private String field1;
        private int field2;
        public TestPortableObject() {
        public TestPortableObject(String field1, int field2) {
            this.field1 = field1;
            this.field2 = field2;
        @Override
        public void readExternal(PofReader pofReader) throws IOException {
            field1 = pofReader.readString(1);
            field2 = pofReader.readInt(2);
        @Override
        public void writeExternal(PofWriter pofWriter) throws IOException {
            pofWriter.writeString(1, field1);
            pofWriter.writeInt(2, field2);
        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            if (o == null || getClass() != o.getClass()) {
                return false;
            TestPortableObject that = (TestPortableObject) o;
            if (field2 != that.field2) {
                return false;
            if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) {
                return false;
            return true;
        @Override
        public int hashCode() {
            int result = field1 != null ? field1.hashCode() : 0;
            result = 31 * result + field2;
            return result;
    }The test server side server-pof-config.xml file
    <pof-config>
        <user-type-list>
            <include>coherence-common-pof-config.xml</include>
            <user-type>
                <type-id>1000</type-id>
                <class-name>com.gridman.test.TestPortableObject</class-name>
            </user-type>
        </user-type-list>
    </pof-config>Now our test code...
    package com.gridman.test;
    import com.tangosol.io.pof.ConfigurablePofContext;
    import com.tangosol.util.Binary;
    import com.tangosol.util.ExternalizableHelper;
    public class Main {
        public static void main(String[] args) {
            // Create an instance of our test PortableObject
            TestPortableObject testPortableObject = new TestPortableObject("testing...", 1234);
            // This is the server side serializer that uses the server side POF config
            ConfigurablePofContext pofContext = new ConfigurablePofContext("server-pof-config.xml");
            // This is the custom client side serializer that just uses the Coherence pof config
            PassThroughPofContext passThroughPofContext = new PassThroughPofContext("coherence-common-pof-config.xml");
            // Serialize our test instance using the server side serializer
            // This would be equivalent to a Binary that would have been sent from the server to the client
            Binary binaryFromServer = ExternalizableHelper.toBinary(testPortableObject, pofContext);
            // Deserialize the binaryFromServer using the client side serializer
            // Just as if the client had recieved this over the wire from the server
            PassThrough passThrough = (PassThrough) ExternalizableHelper.fromBinary(binaryFromServer, passThroughPofContext);
            // Serialise the PassThrough to Binary using the client side serializer
            // as though we are sending the value back over the wire to the server
            Binary serializedPassThrough = ExternalizableHelper.toBinary(passThrough, passThroughPofContext);
            // Deserialize back to an Object using the server side serializer
            TestPortableObject result = (TestPortableObject) ExternalizableHelper.fromBinary(serializedPassThrough, pofContext);
            // The result should be equal to the original testPortableObject
            System.out.println("Result: " + testPortableObject.equals(result));
    }running the above code should print out: Result: true
    This was put together pretty quickly so I'm sure people will comment if I have missed anything.
    JK

  • Java Server/Client Applicaton - problem with sending data back

    Hello!
    I'm trying to write a small server/client chat application in Java. It's server with availability to accept connections from many clients and it's app just for fun... However, I've come up against a huge problem: everything what clients send, arrives to server (I'm sure about that because it is displayed on the Server Application screen) and then server should send it back to all clients but it doesn't work. I have no faintest idea what causes this problem. Maybe you can help me?
    Here is my server app code:
    import java.net.*;
    import java.util.*;
    import java.io.*;
    * @author Robin
    public class Server {
        ServerSocket serw = null;
        Socket socket = null;
        String line = null;
        Vector<ClientThread> Watki = new Vector();
        ClientThread watek = null;
        public Server(int port) {
            try {
                serw = new ServerSocket(port);           
                line = "";
                while(true) {
                    System.out.println("Running. Waiting for client to connect...");
                    socket = serw.accept();
                    System.out.println("Connected with:\n" + socket.getInetAddress() + "\n");
                    watek = new ClientThread(socket);
                    Watki.addElement(watek);
                    Watki.firstElement().Send("doszlo?");
            }catch (IOException e) {
                System.out.println("BLAD: " + e);
        public void sendToAll(String s) {
            for(int i = 0; i < Watki.size(); i++) {
                Watki.elementAt(i).Send(s);
        public class ClientThread extends Thread {
            Socket socket;
            DataInputStream in = null;
            DataOutputStream out = null;
            String line = null;
            public ClientThread(Socket s) {
                try {
                    this.socket = s;
                    in = new DataInputStream(s.getInputStream());
                    out = new DataOutputStream(s.getOutputStream());
                    start();
                }catch (IOException e) {
                    System.out.println("BLAD: " + e);
            public void Send(String s) {
                try {
                    out.writeUTF(s);
                }catch (IOException e) {
                    System.out.println("BLAD: " + e);
            public void run() {
                try {
                    line = "";
                    while (true) {
                        line = in.readUTF();
                        System.out.println(line);
                        sendToAll(line);
                }catch (IOException e) {
                    System.out.println("BLAD: " + e);
        public static void main(String[] args) {
            Server serwer = new Server(5000);
    }And here is client app code:
    import java.net.*;
    import java.util.*;
    import java.io.*;
    * @author Robin
    public class Client implements Runnable {
        Socket socket = null;
        BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
        DataInputStream in = null;
        DataOutputStream out = null;
        String line = null;
        public Client(String host, int port) {
            try {
                System.out.println("Connecting to " + host + ":" + port);
                socket = new Socket(host, port);
                System.out.println("Connected\nTALK:");
                out = new DataOutputStream(socket.getOutputStream());
                in = new DataInputStream(socket.getInputStream());
                line = "";
                while(!line.toLowerCase().equals(".bye")) {
                    line = keyIn.readLine();
                    Send(line);
            }catch (UnknownHostException e) {
                System.out.println("BLAD: " + e);
            }catch (IOException e) {
                System.out.println("BLAD: " + e);
        public void Send(String s) {
            try {
                out.writeUTF(s);
            }catch (IOException e) {
                System.out.println("BLAD: " + e);
        public void run() {
            String loaded = "";
            try {
                while(true) {
                    loaded = in.readUTF();
                    System.out.println(loaded);
            }catch (IOException e) {
                System.out.println("BLAD: " + e);
        public static void main(String[] args) {
            Client client = new Client("localhost", 5000);
    }By the way, this app is mainly written in English language (text that appears on the screen) however in functions I used Polish language (for example: BLAD - it means ERROR in English). Sorry for that :)

    Yeap, I will change those exceptions later, thanks for advice.
    You asked what's going on with it: both applications start with no errors, but when I write something in client side it should be sent to the server and then forwarded to all connected clients but it stops somewhere. However, I added a one line to the server code
    line = in.readUTF();
    System.out.println(line);
    sendToAll(line); and after it reads message from client (no matter which one) it shows that message on the server side screen, then it should send this message to all clients but it doesn't work in this moment. What's confusing: no errors occurs, so it's rather a mistake in my code, but where?
    Edited by: Robin3D on Sep 30, 2009 9:07 AM

  • Oracle server & client deinstallation problems

    my system configuration is:
    windows 2000 professionnal (SP2)
    on this machine, i had the oracle client software installed (verion 8.17)
    i needed the machine to install on it an oracle database, so i deinstalled the client software with the oracle 8.i CD and did not remove three datasources (user DSN driver microsoft ODBC for oracle) that used to work with the previous client version. Then, i installed the oracle server software and created the database.
    the problem at this step is that i could not use the data sources that i had nither could i use the driver to create another one.
    so, for the second time, i deinstalled the server software and installed the client software.
    my second problem, here, (after deinstalling the server software)is that i had the services oracleora81TNSListner and oracleserviceSID that are not removed and i can not stop nor resume
    i'm looking for your answer (what to do with these services and what is the solution for the data sources)
    regards

    user626162 wrote:
    So I need to install the oracle client on C and the Oracle Connection Manager on server B? Would you point me to the document on how to do this?Correct. A good place to start is probably the [Configuring and Administering Oracle Connection Manager|http://download.oracle.com/docs/cd/B19306_01/network.102/b14212/cman.htm#NETAG011] chapter in the Net Services Administrator's Guide.
    Justin

  • Final Cut Server Client Download Problems

    I am attempting to install/run Final Cut Server client on my laptop and Mac tower. The other day the client software worked well on my Mac tower but today no go. I attempted to install the client software on my laptop, I can get to the download screen in a web browser by typing the address of the local server but when I press download the next page appears but no download or dialogue box appears. Also while wrestling with this problem I deleted the client software from my tower. This same issue is now happening on the tower when I try to restore the client software. Possibly related or not I just updated the software to 10.6.7. but tried another machine I have here that is at 10.6.4 with the same result. I also read an old post that described problems with download initiation and how they can be resolved by deleting a few specific resources out of the Java Preference Cash Files. I completed this process which resulted in no evident change.
    BJ

    Try removing the FCSvr client from your local machine and then reinstalling it from the web installer while you are connected via VPN. Run these commands in Terminal to remove it:
    rm -r ~/Library/Caches/Java/
    rm -r ~/Library/Caches/com.apple.finalcutserver/
    rm ~/Library/Preferences/com.apple.finalcutserver.plist
    rm -r ~/Desktop/Final Cut Server.app
    Sometimes my client just won't launch like you are seeing and reinstalling it within whatever network connection I'm using gets it working again.

  • SOAP:1.026 SRT: HTTP-Code 500: ("Internal Server Error")    Exception of class CX_AI_SYSTEM_FAULT

    Hi All,
            while Running Client Proxies from se80 im getting Following error. i already checked all the Services All are active only. can any one suggest me:
    SOAP:1.026 SRT: HTTP-Code 500: ("Internal Server Error")
    Exception of class CX_AI_SYSTEM_FAULT
    RFC Trace:
    **** Trace file opened at 20140630 124650 IST, by disp+work               
        **** Versions SAP-REL 721,0,201 RFC-VER U 3 1460390 MT-SL                 
        XRFC> Begin of user trace                                                 
        XRFC>
        XRFC>                                                                
    <
        XRFC> TRACE SOAP RUNTIME - header                                    
    <
        XRFC>                                                                
    <
        XRFC>
        XRFC> SESSION_ID : 0002425553A5ECFC63B114C4E1000000C0A80141      
        XRFC> TS_CALL
    : 20140630071647.5930180                            
    <
        XRFC> SY_UNAME   : SAPADMIN                                          
    <
        XRFC> HOSTNAME   : SOLAR-DEV                                         
    <
        XRFC> SY_SID
    : DEV                                               
    <
        XRFC> SY_MANDT   : 001                                               
    <
        XRFC> SYS_NR
    : 01                                                
    <
        XRFC> APPLSERVER : SOLAR-DEV_DEV_01                                  
    <
        XRFC> ISPRESCHED : X                                                 
    <
        XRFC> PARENT_ID  : ROOT_CALL_ID                                      
    <
        XRFC> REQ_SIZE   : 1821                                              
    <
        XRFC> RESP_SIZE  : 75                                                
    <
        XRFC> DURATION   : 2246                                              
    <
        XRFC> NETHDRTIME : 2246                                              
    <
    XRFC> CALL_STATE : 2                                                 
    <
    XRFC> ERRORTYPE  : SYSFAIL                                           
    <
    XRFC> ERRORAREA  : COREMSG                                           
    <
    XRFC> CTXDP_TYPE : SOAP_RUNTIME                                      
    <
    XRFC> SYNC_ASYNC : S                                                 
    <
    XRFC> LOCATION   : C                                                 
    <
    XRFC> DIRECTION  : O                                                 
    <
    XRFC> REQ_ID
    : 52EDA553B163C414E1000000C0A80141                  
    <
    XRFC> RESP_ID
    : 00000000000000000000000000000000                  
    <
    XRFC> MSG_STATE  : 114                                               
    <
    XRFC> IF_NAME_I  : YSCO_SAPORDERS_SOAP                               
    <
    XRFC> IF_NS_E
    <
    XRFC> IF_NAME_E  :                                                   
    <
    XRFC> ISSHORTCUT :                                                   
    <
    XRFC> TRC_PATT   : WSTEST                                            
    <
    XRFC> TRC_KEY
    : 50EDA553B163C414E1000000C0A80141                  
    <
    XRFC> TRC_SSID   : DEV_01                                            
    <
    XRFC> TRC_USER   : SAPADMIN                                          
    <
    XRFC> TRC_TS
    : 20140630071647                                    
    <
    XRFC> TRC_COUNT  : 98                                                
    <
    XRFC> TRC_EXT
    <
    XRFC> COMPLETE   : OK                                                
    <
    XRFC> CALLEDPROG : YSCO_SAPORDERS_SOAP                               
    <
    XRFC> SOAP_APPLI : urn:sap-com:soap:runtime:application:client       
    <
    XRFC> CONF_ID
    <
    XRFC> BIND_ID
    <
    XRFC> OP_NAME
    : InsertPPOrders_Development                        
    <
    XRFC> COMM_PATRN : Method:InsertPPOrders_Development                 
    <
    XRFC> OP_NS 
    : http://microsoft.com/webservices/                 
    <
    XRFC> REMADDRESS :                                                   
    <
    XRFC> LP_NAME
    : YSLP1                                             
    <
    XRFC> DT_OBJ
    : YSCO_SAPORDERS_SOAP                               
    <
    XRFC> MEMCONSUMP : 198                                               
    <
    XRFC> BONAME
    <
    XRFC> PROCCOMP   :                                                   
    <
    XRFC> DEPLOYUNIT :                                                   
    <
    XRFC>       <
    XRFC>                                                                
    <
    XRFC> TRACE SOAP RUNTIME - trace records                             
    <
    XRFC>                                                                
    <
    XRFC>       <
    XRFC> E SOAP_RUNTIME 20140630071649.8380110 : CL_SOAP_RUNTIME_CLIENT 
    <
    XRFC> ->EXECUTE_PROCESSING Exception handling in SOAP runtime        
    <
    XRFC>                                                                
    <
    XRFC>                                                                
    <
    XRFC> E SOAP_APPLICATION 20140630071649.8382410 : CL_SOAP_APPLICATION
    <
        XRFC> _CLIENT ->IF_SOAP_APPLICATION_CS~EXECUTE_PROCESSING Exception  
    <
        XRFC> handling in SOAP runtime                                       
    <
        XRFC>                                                                
    <
        XRFC>                                                                
    <
        XRFC> E HTTP_TRANSPORT_BINDING 20140630071649.8368980 : CL_SOAP_HTTP 
    <
        XRFC> _TPBND_ROOT ->HANDLE_STATUS_CODE Received return code 500 (    
    <
        XRFC> Internal Server Error )                                        
    <
        XRFC>                                                                
    <
        XRFC>                                                                
    <
        XRFC> E SOAP_RUNTIME 20140630071649.8379970 : CL_SOAP_RUNTIME_CLIENT 
    <
        XRFC> ->EXECUTE_PROCESSING A SOAP Runtime Core Exception occurred in 
    <
        XRFC> method get_http_headers of class CL_SOAP_HTTP_TPBND_ROOT at    
    <
        XRFC> position id 3 with internal error id 1026 and error text SRT:  
    <
        XRFC> HTTP-Code 500: ("Internal Server Error") (fault location is 1 ).
    <
        XRFC>                                                                
    <
        XRFC>                                                                
    <
        XRFC> E SOAP_APPLICATION 20140630071649.8382290 : CL_SOAP_APPLICATION
    <
        XRFC> _CLIENT ->IF_SOAP_APPLICATION_CS~EXECUTE_PROCESSING A SOAP Runtime  <
        XRFC> Core Exception occurred in method get_http_headers of class    
    <
        XRFC> CL_SOAP_HTTP_TPBND_ROOT at position id 3 with internal error id
    <
        XRFC> 1026 and error text SRT: HTTP-Code 500: ("Internal Server Error")   <
        XRFC> (fault location is 1 ).                                        
    <
        XRFC>                                                                
    <
    Find The Attachment for error:

    Hi Brahmaji,
    i also faced with the above problem, activete the srt services in SICF Transaction.
    Regards,
    Kumar.
    Edited by: kmikkili on Nov 18, 2009 11:39 PM

  • Non-blocking Server/Client is blocking...?!

    First, a simple question:
    Why in most example code using Selectors, when iterating over the Set returned by Selector.selectedKeys() does the currently selected SelectionKey get removed from the Iterator? I see it all the time, but since the SelectionKey is still bound to the underlying Selector it seems to not really do anything.
    Now to my main problem:
    I been working with 1.4 for a week now trying to implement a simple test server/client, whereby the server constantly sends out the current time to any subscribing clients, who in turn display the time to stdout. Pretty straight forward, huh?
    Well, everything seems to go fine...once. The Server accepts the client connection, sends out a the current time, the client (only one for now) receives it, displays to the screen, but then both server and client block on the Selector.select() method.
    If I shut down the client, the server then continues through the select() method, finding one SelectionKey, tries to write to it and throws an IOException (since the client is no more). I'm catching that exception and then removing the channel from the Selector, so that the server may continue to service requests.
    When starting a second client while the first is still running causes the following sequence of events:
    Server: starts up
    ClientA: connects to server
    Server: broadcasts the time
    ClientA: displays time
    // nothing else happens until...
    ClientB: connects to server
    Server: broadcasts the time
    ClientA: displays time
    ClientB: displays time
    //everything blocks again...
    ClientA: disconnects from server
    Server: broadcasts the time
    ClientB: displays time
    As you can see it seems everything blocks until a client does something (connect/disconnect).
    I will post code if anyone asks, but I don't want to spam the board if no one is willing to help me.
    -Justin

    You got it!
    //   ********** SERVER **********
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.nio.ByteBuffer;
    import java.nio.channels.CancelledKeyException;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Date;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.Set;
    public class TestServer
      private static final int DEFAULT_PORT = 9999;
      public static void main(String[] args)
        TestServer s = new TestServer();
      }//end of main(String[])
      public TestServer()
        this(DEFAULT_PORT);
      }// end of TestServer()
      public TestServer(int port)
        InetSocketAddress addr = new InetSocketAddress(port);
        try
          Selector acceptSelector = Selector.open();
          Selector broadcastSelector = Selector.open();
          ConnectionList connections = new ConnectionList(broadcastSelector);
          Acceptor a = new Acceptor(acceptSelector, addr, connections);
          Broadcaster b = new Broadcaster(broadcastSelector, connections);
          a.start();
          b.start();
        }// end of try
        catch (Exception ex)
          ex.printStackTrace();
        }// end of catch
      }// end of TestServer(int)
      private static String status(Selector s)
        StringBuffer sb = new StringBuffer(100);
        sb.append("Selector: ");
        Set keys = s.keys();
        sb.append("\n\tNum Keys: ");
        sb.append(keys.size());
        Iterator iter = keys.iterator();
        int i = 0;
        while (iter.hasNext())
          try
            sb.append("\n\t[");
            sb.append(i++);
            sb.append("]:");
            SelectionKey key = (SelectionKey)iter.next();
            sb.append(" acceptable=");
            sb.append(key.isAcceptable());
            sb.append(" connectable=");
            sb.append(key.isConnectable());
            sb.append(" readable=");
            sb.append(key.isReadable());
            sb.append(" writable=");
            sb.append(key.isWritable());
          }// end of try
          catch (CancelledKeyException cke)
            sb.append("*** CANCELLED KEY");
          }// end of catch
        }// end of while
        return sb.toString();
      }// end of status(Selector)
      class Broadcaster extends Thread
        private final String TF = Broadcaster.class.getName();
        private int BUFFER_SIZE = 2048;
        private Selector selector_;
        private ConnectionList connections_;
        private ByteBuffer buffer_;
        public Broadcaster(Selector selector, ConnectionList connections)
          super("Broadcaster");
          selector_ = selector;
          connections_ = connections;
          buffer_ = ByteBuffer.allocateDirect(BUFFER_SIZE);
        public void run()
          while (true)
            try
              registerNewChannels();
              System.out.println("BroadcasterThread: Before select() "+status(selector_));
              System.out.println("BroadcasterThread: Selecting...");
              int keysReady = selector_.select();
              System.out.println("BroadcasterThread: After select() "+status(selector_));
              System.out.println("BroadcasterThread: "+keysReady+" ready Key(s)");
              if (keysReady > 0)
                transmit();
              }// end of if
            }// end of try
            catch (Exception ex)
              ex.printStackTrace();
              return;
            }// end of catch
          }// end of while
        protected void registerNewChannels()
        throws Exception
          SocketChannel channel = null;
          while (null != (channel = connections_.removeFirst()))
            channel.configureBlocking(false);
            channel.register(selector_, SelectionKey.OP_WRITE);
            System.out.println("BroadcasterThread: Registered connection from " + channel.socket().getInetAddress());
          }// end of while 
        }// end of registerNewChannels()
        public void transmit()
        throws Exception
          Set readyKeys = selector_.selectedKeys();
          System.out.println("BroadcasterThread: Selected Keys: "+readyKeys.size());
          SelectionKey tempKey = null;
          SocketChannel tempChannel = null;
          fillBuffer();
          for (Iterator i = readyKeys.iterator(); i.hasNext(); )
            tempKey = (SelectionKey)i.next();
            tempChannel = (SocketChannel)tempKey.channel();
            if (tempKey.isWritable())
              System.out.println("BroadcasterThread: Key selected is Writable");
              try
                tempChannel.write(buffer_);
                System.out.println("BroadcasterThread: Sent message to "+tempChannel.socket().getInetAddress());
              }// end of try
              catch (IOException ioe)
                System.err.println("BroadcasterThread: Lost Connection");
                tempChannel.close();
              }// end of catch
            }// end of if
            else
              System.out.println("BroadcasterThread: Key selected is not Writable");
            }// end of else
          }// end of for
          buffer_.clear();
        }// end of transmit()
        private void fillBuffer()
          buffer_.clear();
          /* Place Date in Buffer */
          long time = System.currentTimeMillis();
          Date d = new Date(time);
          System.out.println("BroadcasterThread: Broadcasting "+d);
          String date = d.toString()+"\n";
          byte[] datebuff = date.getBytes();
          buffer_.put(datebuff);
          /* Prepare for read operations */
          buffer_.flip();
        }// end of fillBuffer()
      }//end of inner class Broadcaster
      class Acceptor extends Thread
        private Selector selector_;
        private ConnectionList connList_;
        private final String TF = Acceptor.class.getName();
        public Acceptor(Selector selector, InetSocketAddress address, ConnectionList connList)
          super("Acceptor");
          selector_ = selector;
          connList_ = connList;
          try
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);
            ssc.socket().bind(address);
            System.out.println("AcceptorThread: Bound to " + address);
            ssc.register(selector_, SelectionKey.OP_ACCEPT);
          }// end of try
          catch (Exception ex)
            ex.printStackTrace();
          }// end of catch
        public void run()
          while (true)
            try
              System.out.println("AcceptorThread: Selecting...");
              int keysReady = selector_.select();// block till a channel is ready
              System.out.println("AcceptorThread: "+keysReady+" Keys Ready");
              if (keysReady > 0)
                acceptPendingConnections();
              }// end of if
            catch (Exception ex)
              ex.printStackTrace();
        protected void acceptPendingConnections()
        throws Exception
          Set readyKeys = selector_.selectedKeys();
          System.out.println("AcceptorThread: Selected "+readyKeys.size()+" Keys");
          for (Iterator i = readyKeys.iterator(); i.hasNext(); )
            SelectionKey key = (SelectionKey)i.next();
            i.remove();  
            ServerSocketChannel readyChannel = (ServerSocketChannel)key.channel();
            SocketChannel incomingChannel = readyChannel.accept();
            System.out.println("AcceptorThread: Connection from " + incomingChannel.socket().getInetAddress());
            connList_.add(incomingChannel);
          }// end of for
        }// end of acceptPendingConnections()
      }// end of inner class Acceptor
      class ConnectionList
        private LinkedList list_;
        private Selector selectorToNotify_;
        public ConnectionList(Selector toNotify)
          list_ = new LinkedList();
          selectorToNotify_ = toNotify;
        }// end of ConnectionList(Selector)
        public synchronized void add(SocketChannel newlyConnectedChannel)
          list_.add(newlyConnectedChannel);
          selectorToNotify_.wakeup();
        }// end of add(SocketChannel)
        public synchronized SocketChannel removeFirst()
          SocketChannel first = null;
          if (list_.size() > 0)
            first = (SocketChannel)list_.removeFirst();
          }//end of if
          return first;
        }// end of removeFirst()
      }// end of inner class ConnectionList
    }// end of class TestServer
    //   ********** CLIENT **********
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.CancelledKeyException;
    import java.nio.channels.Channels;
    import java.nio.channels.ReadableByteChannel;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.nio.channels.WritableByteChannel;
    import java.util.Iterator;
    import java.util.Set;
    public class TestClient
      public static final String TF = TestClient.class.getName();
      private static final String DEFAULT_SERVER_IP = "127.0.0.1";
      private static final int DEFAULT_SERVER_PORT = 9999;
      private InetSocketAddress serverAddr_; 
      private Selector connectSelector_;
      private Selector readSelector_; 
      private WritableByteChannel outputChannel_; 
      private ByteBuffer receiveBuffer_;
      private SocketChannel serverChannel_;
      public static void main(String[] args)
        TestClient c = new TestClient();
      }// end of main(String[])
      public TestClient()
        this(DEFAULT_SERVER_IP, DEFAULT_SERVER_PORT);
      }// end of TestClient()
      public TestClient(String ip, int port)
        try
          serverAddr_ = new InetSocketAddress(ip, port);
          connectSelector_ = Selector.open();
          readSelector_ = Selector.open();
          outputChannel_ = Channels.newChannel(System.out);
          receiveBuffer_ = ByteBuffer.allocateDirect(512);
          connect();
          run();
        }// end of try
        catch (Exception ex)
          ex.printStackTrace();
        }// end of catch
      }// end of TestClient(String, int)
      private void connect()
      throws Exception
        serverChannel_ = SocketChannel.open();
        serverChannel_.configureBlocking(false);
        serverChannel_.connect(serverAddr_);
        serverChannel_.register(connectSelector_, SelectionKey.OP_CONNECT);
        int numKeys = 0;
        while (numKeys <= 0)
          System.out.println("connect(): Selecting...");
          numKeys = connectSelector_.select();
          System.out.println("connect(): "+numKeys+" ready Key(s)");
          Set readyKeys = connectSelector_.selectedKeys();
          System.out.println("connect(): Selected Keys: "+readyKeys.size());
          if (numKeys > 0)
            SelectionKey tempKey = null;
            SocketChannel tempChannel = null;
            Iterator i = readyKeys.iterator();
            while (i.hasNext())
              tempKey = (SelectionKey)i.next(); 
              i.remove();  
              tempChannel = (SocketChannel)tempKey.channel();
              if (tempKey.isConnectable())
                System.out.println("connect(): Key selected is Connectable");
                if (tempChannel.isConnectionPending())
                  System.out.println("connect(): Connection Pending");
                  tempChannel.finishConnect();
                  System.out.println("connect(): Connection Completed");
                }// end of if
              }// end of if
              else
                System.out.println("connect(): Key selected is not Connectable");
              }// end of else
            }// end of while
          }// end of if
        }// end of while
      }// end of connect()
      private void run()
      throws Exception
        serverChannel_.register(readSelector_, SelectionKey.OP_READ);
        while (true)
          System.out.println("run(): Before select() "+status(readSelector_));
          System.out.println("run(): Selecting...");
          int numKeys = readSelector_.select();
          System.out.println("run(): After select() "+status(readSelector_));
          System.out.println("run(): "+numKeys+" Ready Key(s)");
          if (numKeys > 0)
            processKeys();
          }// end of if
        }// end of while
      }// end of run()
      private void processKeys()
      throws Exception
        Set readyKeys = readSelector_.selectedKeys();
        System.out.println("processKeys(): Selected Keys: "+readyKeys.size());
        SelectionKey tempKey = null;
        SocketChannel tempChannel = null;
        for (Iterator i = readyKeys.iterator(); i.hasNext(); )
          tempKey = (SelectionKey)i.next();
          tempChannel = (SocketChannel)tempKey.channel();
          if (tempKey.isReadable())
            System.out.println("processKeys(): Key selected is Readable");
            try
              tempChannel.read(receiveBuffer_);
              receiveBuffer_.flip();
              outputChannel_.write(receiveBuffer_);
              receiveBuffer_.clear();
            }// end of try
            catch (IOException ioe)
              System.out.println("processKeys(): Lost Connection");
              tempKey.cancel();
            }// end of catch
          }// end of if
          else
            System.out.println("processKeys(): Key selected is not Readable");
          }// end of else
        }// end of for
      }// end of processKeys()
      private static String status(Selector s)
        StringBuffer sb = new StringBuffer(100);
        sb.append("Selector: ");
        Set keys = s.keys();
        sb.append("\n\tNum Keys: ");
        sb.append(keys.size());
        Iterator iter = keys.iterator();
        int i = 0;
        while (iter.hasNext())
          try
            sb.append("\n\t[");
            sb.append(i++);
            sb.append("]:");
            SelectionKey key = (SelectionKey)iter.next();
            sb.append(" acceptable=");
            sb.append(key.isAcceptable());
            sb.append(" connectable=");
            sb.append(key.isConnectable());
            sb.append(" readable=");
            sb.append(key.isReadable());
            sb.append(" writable=");
            sb.append(key.isWritable());
          }// end of try
          catch (CancelledKeyException cke)
            sb.append("*** CANCELLED KEY");
          }// end of catch
        }// end of while
        return sb.toString();
      }// end of status(Selector)
    }// end of class TestClient

  • Need an example of server / client program with swing interface

    Hi!
    After a lot of trying i still haven't managed to create a server client program using swing components ...
    can someone write a mini application to demonstrate how this can be done?
    i would like to have a frame with a button a texField for input and a textAread for the output
    What i have in mind is the following ..
    say im the server
    i write something in the textField and then i press the button
    then the information written in the textFiled is passed to the client who shows it in his textArea
    The same thing goes on with the client (he can write something in his own textField and when he presses the button the info is passed at the
    server who puts it in his textArea) and vice versa.
    i have written many classes that trying unsuccessfully to do that ... below i show my last attempt ...
    I would appreciate if you could write a small application which it could to this.
    The whole idea is to create a turn based game ( i have implemented the game engine and graphics and i try to add the internet function)
    Here is the code ...( i would appreciate if you write a new code instead of trying to correct mine ( which i think it's impossible) in order to use it as a general example)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    @SuppressWarnings("serial")
    *  In order to have a more gereral program instead of passing strings between the server
    *  and the client a pass an MyObjext object.  The MyObject class has an integer and a String
    *  (which is always the same) field . At the textField i write an integer number and i
    *  make a new MyObject which i want to pass to the server or the client and vice versa.
    *  The textArea shows the integer value of the MyObject which was passed from the server /client
    public class MyUserInterface extends JFrame {
         MyObject returnObject;
         JTextField myTextField;
         JTextArea te ;
         ClientGame cg;
         ServerGame sg;
          * used to determine if the current instance is running as a client or host
         boolean isHost;
         //The constructor of the client
         public MyUserInterface(ClientGame cg){
              this("Client");
              this.cg = cg;
              isHost = false;
         //The constructor of the server
         public MyUserInterface(ServerGame sg){
              this("Server");
              this.sg = sg;
              isHost = true;
         //The general constructor used both by client and server ..
         // it initializes the GUi components and add an actionListenr to the button
         public MyUserInterface(String str) {
              super(str);
              myTextField = new JTextField(2);
              te = new JTextArea();
              te.setPreferredSize(new Dimension(100,100));
              JButton okButton = new JButton("Ok");
              okButton.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e) {
                        try{
                             int a = Integer.parseInt(MyUserInterface.this.myTextField.getText());
                             System.out.println(a);   //used to control the flow of the program
                                  MyUserInterface.this.returnObject = new MyObject(a);
                             //sends the data
                             sendData();
                             //waiting for response...
                             getData();
                             catch(Exception ex){System.out.println("Error in the UI action command" +
                                                                ex.printStackTrace();}
              JPanel panel =  new JPanel(new FlowLayout());
              panel.add(okButton);
              panel.add(myTextField);
              panel.add(te);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              getContentPane().add(panel);
              pack();
              setVisible(true);
         protected MyObject getReturnObject() {
              return returnObject;
         public void sendData(){
              new Thread(new Runnable() {
                   @Override
                   public void run() { 
                        if (!isHost)cg.sentData(returnObject);    //using the Servers out and in methods
                        else sg.sentData(returnObject);                    //using the Clients out and in methods
                        System.out.println("data sending");
         public MyObject getData(){
              MyObject obj;
              System.out.println("Retrieveing Data");
              if (!isHost)obj = (MyObject)cg.getData();
              else obj = (MyObject)sg.getData();
              System.out.println(" data retrieved  = "+ obj.getInt());  //just to control how the code flows
              te.setText(obj.getInt()+"");       
              return obj;
         public static void main(String[] args) {
              *Initiating the Server
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        ServerGame sg = new ServerGame();
                        new MyUserInterface(sg);
              }).start();     
               * Initiating the Client
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        ClientGame cg = new ClientGame("192.168.178.21");   //<----in case you run my code
                                                                          //..don't forget to change to your
                        new MyUserInterface(cg);                              //ip
              }).start();
    import java.io.*;
    import java.net.*;
    public class ClientGame {
         String ipAddress;
         Socket clientSocket = null;
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
         public ClientGame(String ipAddress) {
              this.ipAddress = ipAddress;
              try {
                   System.out.println("Connecting To Host");
                 clientSocket = new Socket(InetAddress.getByName(ipAddress),4444);
                System.out.println("Host Found ...Io initializaton");
                out = new ObjectOutputStream(clientSocket.getOutputStream());
                in = new ObjectInputStream(clientSocket.getInputStream());
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: taranis.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: taranis.");
                System.exit(1);
         public Object getData(){
              Object fromServer = null ;
              do{
                 try {
                      fromServer = in.readObject();
                 catch(ClassNotFoundException ex){}
                  catch(IOException e){}
              }while(fromServer==null);
              return fromServer;        
         public void sentData(final Object obj){
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        try{
                             out.writeObject(obj);
                        catch(IOException e){}
              }).start();
         public void terminateConnection(){
              try{
                   out.close();
                   in.close();
                   clientSocket.close();
              catch (IOException e){}
    public class ServerGame {
         ServerSocket serverSocket;
         Socket clientSocket;
         ObjectOutputStream out = null;
        ObjectInputStream in = null;
         public ServerGame() {
              try{
                   serverSocket = new ServerSocket(4444);
                   clientSocket = serverSocket.accept();
                   out =  new ObjectOutputStream(clientSocket.getOutputStream());
                in = new ObjectInputStream(clientSocket.getInputStream());
              catch(IOException e){System.out.println("IOException in ServerGame");}
         public Object getData(){
              Object fromClient = null ;
              do{
                 try {
                      fromClient = in.readObject();
                 catch(ClassNotFoundException ex){}
                  catch(IOException e){}
              }while(fromClient==null);
             return fromClient;        
         public void sentData(final Object obj){
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        try{
                   out.writeObject(obj);
              catch(IOException e){}
              }).start();
         public void terminateConnection(){
              try{
                   out.close();
                   in.close();
                   clientSocket.close();
                   serverSocket.close();
              catch (IOException e){}
         public static void main(String[] args) {
              new ServerGame();
    import java.io.Serializable;
    * this is a test object
    * it has a String field and a value
    *  The string is always the same but the integer value is defined in the constructor
    public class MyObject implements Serializable{
         private static final long serialVersionUID = 1L;
         String str;
         int myInt;
         MyObject(int a){
              str = "A String";
              myInt = a;
         public int getInt(){
              return myInt;
    }

    Pitelk wrote:
    I believe that a good code example can teach you things ;that you would need many days of searching; in no timeSo lets write one small example.. Ill help a little, but you do most of the work.
    jverd approach is deffenetly the way to go.
    jverd wrote:
    * Write a very small, simple Swing program with an input area, an output area, and a button. When you click the button, what's in the input area gets copied over to the output area.This part is partially done.
    * Write a very small, simple client/server program without Swing. It should just send a couple of hardcoded messages back and forth.And this part is for you(Pitelk) to continue on. I cannot say that this is the best way. or that its good in any way. I do however like to write my client/server programs like this. And perhaps, and hopefully, Ill learn something new from this as well.
    This is how far I got in about 10-20min..
    package client;
    * To be added;
    * A connect method. That connects the client to the server and
    * opens up both the receive and transmit streams. After doing that
    * the an instance of the ServerListener class should be made.
    * Also an disconnect method could be usable. But thats a later part.
    public class TestClass1 {
    package utils;
    import java.io.ObjectInputStream;
    import client.TestClass1;
    * This class is meant to be listening to all responses given from
    * the server to the client. After a have received data from the
    * server. It should be forwarded to the client, in this case
    * TestClass1.
    public class ServerListener implements Runnable {
         public ServerListener(ObjectInputStream in, TestClass1 tc) {
         @Override
         public void run() {
              while(true) {
    package server;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.List;
    * This class should handle all data sent to the server from the clients.
    class Server implements Runnable {
         private static List<ObjectOutputStream> outStreams = new ArrayList<ObjectOutputStream>();
         private Socket client = null;
         public Server(Socket client) {
              this.client = client;
         @Override
         public void run() {
              while(true) {
    * The meaning of this class is to listen for clients trying to connect
    * to the server. Once connection is achieved a new thread for that client
    * should be made to listen for data sent by the client to the server.
    public class ChatServer implements Runnable {
         @Override
         public void run() {
              while(true) {
    package utils;
    import java.io.Serializable;
    @SuppressWarnings("serial")
    public class MyObject implements Serializable {
         private String mssg;
         private String clientID;
         private String clientName;
         public MyObject(String mssg, String clientID, String clientName) {
              this.mssg = mssg;
              this.clientID = clientID;
              this.clientName = clientName;
         //Generate getters and setters..
    }Continue on this, and when you get into problems etc post them. Also show with a small regular basis how far you have gotten with each class or it might be seen as you have lost intresst and then this thread is dead.
    EDIT: I should probably also say that Im not more than a java novice, at the verry most. So I cannot guarantee that I alone will be able to solve all the problems that might occure during this. But Im gonna try and help with the future problems that may(most likely will) occure atleast(Trying to reserve my self incase of misserable failiure from me in this attempt).
    Edited by: prigas on Jul 7, 2008 1:47 AM

  • Compiling server-client with eclipse

    hi. i'm new to java programming and i'm using eclipse. i have 2 simple programmes, one for a server and another for a client and would like to use them to communicate with each other. i have an error message with both programs.. i think that there is a prblem with my server program...is there anything i need to add to get it running or is there anything in particular needed when using eclipse to run server/client programs? here is the code:
    import java.io.*;
    import java.net.*;
    public class Serveur {
         public static void main(String[] args) {
              try{
              ServerSocket ss= new ServerSocket(1500);
              Socket sc= ss.accept();
              System.out.println("connection etablie");
              PrintWriter flux_sortant = new PrintWriter(sc.getOutputStream());
              flux_sortant.println("coucou j'ecris");
              //ss.close();
              //sc.close();
              catch (IOException e){
                   System.out.println("Connection non etablie");
    and for the client:
    import java.io.*;
    import java.net.*;
    public class Client {
         public static void main(String[] args) {
              try{
                   Socket s= new Socket("local host",1500);
                   BufferedReader flux_entrant= new BufferedReader(new InputStreamReader(s.getInputStream()));
                   System.out.println("J'ai lu:" + flux_entrant.readLine());
              catch (IOException e){
                   System.out.println("probleme de connection");
    thanks

    Hello,
    if you want your server programm to listen for incoming connections all the time, then you shouldn't close your ServerSocket because it is accepting the connections.
    I would try something like this:
    public class Serveur implements Runnable{
           private boolean running = true;
           private ServerSocket ss;
           public Serveur(){
                   ss = new ServerSocket(1500);
          public static void main(String[] args){
                  new Thread(new Serveur()).start();
        public void run(){
                while(running){
                        Socket sc = ss.accept();
                        System.out.println("Connection established");
                       PrintWriter writer = new PrintWriter(sc.getOutputStream());    
                       writer.println("Blah");
                       sc.close();           
    }This server would accept a connection send back "Blah" and close the connection to the client.
    hope that helps...
    greetz
    Message was edited by:
    n3bul4

  • Server/Client connection using an actionListener

    Hey guys,
    New to this board, so hopefully I can be of assistance :)
    What I am currently working on is a networked Monopoly game. My part of the assignment is to create a simple game lobby (just GUI based, buttons, action listeners, etc) where players can create games and join games already created.
    What I have is this. When a player clicks on the "Create Game" button, an anonomus inner action listener will detect the push and create a hosted game (Server side connection). When a player clicks on the newly created game, they will be a joined player (Client side connection).
    The problem is this, keep in mind that I have created a very, very simple server/client chat to test this out. When a Socket is created for the clients to connect to upon the Create Game button push, my program essentially just hangs. Nothing happens at all.
    Here are the 3 classes I used. I understand this is probably not the most efficient way to post, but this is the only way you can see what I exactly have. I took out all my GUI stuff to make it easier to follow (if you want me to post full classes I can):
    Thanks for all the help!
    - Ry
    //package Mackopoly;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.io.EOFException;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.JFrame;
    public class gameList extends JFrame {
        MackPlayer tc1;
        MackPlayer tc2;
        MackPlayer tc3;
        HostPlayer ts1;
        HostPlayer ts2;
        HostPlayer ts3;
        private String temp = ""; //used to display chat area
        private int gameCounter = 0; //number of games created
        private boolean game1Started = false;
        private boolean game2Started = false;
        private boolean game3Started = false;
        public void start()
        //Sets up the screen
            enterField.addActionListener(
            new ActionListener()
                public void actionPerformed(ActionEvent ae)
                    if (ae.getSource() == enterField)
                        temp = enterField.getText();
                        chatBox.append(temp + "\n");
                        enterField.setText("");
            createGame.addActionListener(
            new ActionListener()
                public void actionPerformed(ActionEvent ae)
                    if (ae.getSource() == createGame)
                        gameCounter++;
                        if(gameCounter == 1)
                            //create a new host game on the server
                            //instanciate an object accordingly
                            game1.setText("Game " + gameCounter + "started!");
                            game1Started = true;
                                  ts1 = new HostPlayer();
                            ts1.execute();
                        else if(gameCounter == 2)
                            game2.setText("Game " + gameCounter + "started!");
                            game2Started = true;
                                  ts2 = new HostPlayer();
                            ts2.execute();
                        else if(gameCounter == 3)
                            game3.setText("Game " + gameCounter + "started!");
                            game3Started = true;
                                  ts3 = new HostPlayer();
                             ts3.execute();
                        else
                            System.out.println("games full");
            joinGame1.addActionListener(
            new ActionListener()
                public void actionPerformed(ActionEvent ae)
                    if (ae.getSource() == joinGame1)
                        if(game1Started == false)
                            JOptionPane.showMessageDialog(null,"Start a game!");
                        if(game1Started == true)
                            JOptionPane.showMessageDialog(null,"Joined!");
                            tc1 = new MackPlayer("Game 1");
                            tc1.startClient();
            joinGame2.addActionListener(
            new ActionListener()
                public void actionPerformed(ActionEvent ae)
                    if (ae.getSource() == joinGame2)
                        if(game2Started == false)
                            JOptionPane.showMessageDialog(null,"Start a game!");
                        if(game2Started == true)
                             JOptionPane.showMessageDialog(null,"Joined!");
                            tc2 = new MackPlayer("Game 2");
                            tc2.startClient();
            joinGame3.addActionListener(
            new ActionListener()
                public void actionPerformed(ActionEvent ae)
                    if (ae.getSource() == joinGame3)
                        if(game3Started == false)
                            JOptionPane.showMessageDialog(null,"Start a game!");
                        if(game3Started == true)
                             JOptionPane.showMessageDialog(null,"Joined!");
                            tc3 = new MackPlayer("Game 3");
                            tc3.startClient();
        }//End start method
    }//End of my class
    import java.awt.*;
    import java.awt.event.*;
    import java.net.Socket;
    import java.net.InetAddress;
    import java.io.IOException;
    import javax.swing.*;
    import java.util.Formatter;
    import java.util.Scanner;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    //Imports necessary packages
    public class MackPlayer extends JFrame implements Runnable
    //Client class
         private JTextField idField;
         private JTextArea displayArea;
         private JTextField guessArea;
         private JPanel panel2;
         private Socket connection;
         private Scanner input;
         private Formatter output;
         private String Host;
         private String myMark;
         private boolean myTurn;
         private final String X_MARK = "1";
         private final String O_MARK = "2";
         public MackPlayer(String host)
              Host = host;
              displayArea = new JTextArea(10,30);
              displayArea.setEditable(false);
              add(new JScrollPane(displayArea), BorderLayout.SOUTH);
              //Creates the message area
              idField = new JTextField();
              idField.setEditable(false);
              add(idField, BorderLayout.NORTH);
              //Creates the name field
              guessArea = new JTextField(10);
              guessArea.setEditable(false);
              add(new JScrollPane(guessArea), BorderLayout.CENTER);
              //Creates the guess area
              panel2 = new JPanel();
              panel2.add(guessArea, BorderLayout.CENTER);
              add(panel2, BorderLayout.CENTER);
              setSize(350, 275);
              setVisible(true);
              TextHandler tHandler = new TextHandler();
              idField.addActionListener(tHandler);
              guessArea.addActionListener(tHandler);
              //Adds the area's to the handler
              startClient();
         public void startClient()
         //Gets connection and starts thread
              try
                   connection = new Socket(InetAddress.getByName(Host), 12345);
                   input = new Scanner(connection.getInputStream());
                   output = new Formatter(connection.getOutputStream());
              catch(IOException e)
                   e.printStackTrace();
              ExecutorService worker = Executors.newFixedThreadPool(1);
              worker.execute(this);
         public void run()
              myMark = input.nextLine();
              SwingUtilities.invokeLater(
              new Runnable()
                   public void run()
                        idField.setText("Enter name here");
                        guessArea.setText("Enter guess");
                        //Default text
              );//end call
              myTurn = (myMark.equals(X_MARK));
              while(true)
                   if(input.hasNextLine())
                        processMessage(input.nextLine());
         private void processMessage(String message)
         //Handles all possible messages from the server
              if(message.equals("Guess too low."))
                   displayMessage("Guess too low\n");
              else if(message.equals("Guess too high."))
                   displayMessage("Guess too high\n");
              else if(message.equals("You Win!"))
                   displayMessage("You Win!\n");
              else if(message.equals("Other player connected.  Your turn."))
                   displayMessage("Other player connected.  Your turn\n");
                   guessArea.setEditable(true);
              else if(message.equals("Name1"))
                   displayMessage("Enter your name.\n");
                   idField.setEditable(true);
              else if(message.equals("Name2"))
                   displayMessage("Enter your name.\n");
                   idField.setEditable(true);
              else if(message.equals("Player 2 has entered name"))
                   displayMessage("Player 2 has entered name.  Your turn\n");
                   guessArea.setEditable(true);
              else if(message.equals("Invalid guess, try again"))
                   displayMessage(message + "\n");
                   myTurn = true;
                   guessArea.setEditable(true);
              else if(message.equals("Opponent guessed"))
                   int sw = input.nextInt();
                   displayMessage("Opponent guessed " + sw);
                   sendGuess(sw);
                   displayMessage("\nOpponent moved.  Your turn.\n");
                   guessArea.setEditable(true);
              else if(message.equals("Opponent guessed and won"))
                   int sw = input.nextInt();
                   displayMessage("Opponent guessed and won with number " + sw);
                   sendGuess(sw);
                   guessArea.setEditable(false);
              else
                   displayMessage(message + "\n");
         private void displayMessage(final String messageToDisplay)
              SwingUtilities.invokeLater(
              new Runnable()
                   public void run()
                        displayArea.append(messageToDisplay);
         public void sendGuess(int guess)
              if(myTurn)
                   output.format("%d\n", guess);
                   output.flush();
         private class TextHandler implements ActionListener
         //Handles the fields
              public void actionPerformed(ActionEvent event)
                   if(event.getSource() == idField)
                        idField.setEditable(false);
                        output.format("%s\n", idField.getText());
                        output.flush();
                        myTurn = false;
                        //Sends the name to the server
                        //Sets text to the name and sets it uneditable and sets turn to false
                   if(event.getSource() == guessArea)
                        guessArea.setEditable(false);
                        output.format("%s\n", guessArea.getText());
                        output.flush();
                        guessArea.setText("");
                        myTurn = false;
                        //Send the guess to the server
                        //Clears the past guess from the screen
    import java.awt.BorderLayout;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.io.IOException;
    import java.util.*;
    import javax.swing.*;
    import java.util.concurrent.*;
    import java.util.concurrent.locks.*;
    //Imports necessary packages
    public class HostPlayer extends JFrame
    //Server class
         private JTextArea outputArea;
         private Player[] players;
         private ServerSocket server;
         private int currentPlayer;
         private final static int PLAYER_1 = 0;
         private final static int PLAYER_2 = 1;
         private final static String[] MARKS = { "1", "2"};
         private ExecutorService runGame;
         private Lock gameLock;
         private Condition otherPlayerConnected;
         private Condition otherPlayerTurn;
         private Random generator = new Random();
         private int randomNumber;
         private String p1Name, p2Name;
         //Variables
         public HostPlayer()
              super("Guessing game");
              //Title of server window
              runGame = Executors.newFixedThreadPool(2);
              //Hanldes up to two clients
              gameLock = new ReentrantLock();
              //The lock
              otherPlayerConnected = gameLock.newCondition();
              otherPlayerTurn = gameLock.newCondition();
              //The condition variables
              players = new Player[2];
              currentPlayer = PLAYER_1;
              //The players
              try
                   server = new ServerSocket(12345, 2);
              catch(IOException e)
                   e.printStackTrace();
                   System.exit(1);     
              //Establishes server
              randomNumber = generator.nextInt(10);
              //The number to be guessed 0-10
              outputArea = new JTextArea();
              add(outputArea, BorderLayout.CENTER);
              outputArea.setText("Server awaiting connections \n");
              //The output area
              displayMessage("The number is " + randomNumber + " \n");
              //Prints out what the number is
              setSize(300, 300);
              setVisible(true);
              //Sets the size of the server window
         public void execute()
              for(int i = 0; i < players.length; i++)
                   try     
                        players[i] = new Player(server.accept(), i);
                        runGame.execute(players);
                        //Runs the threads to handle clients
                   catch(IOException e)
                        e.printStackTrace();
                        System.exit(1);
              gameLock.lock();
              try
                   players[PLAYER_1].setSuspended(false);
                   otherPlayerConnected.signal();
              finally
                   gameLock.unlock();
         private void displayMessage(final String messageToDisplay)
         //Function that displays messages
              //Class + method that can update the GUI for threads
              SwingUtilities.invokeLater(
              new Runnable()
                   public void run()
                        outputArea.append(messageToDisplay);
         public boolean validateAndMove(int guess, int player)
         //Function that determines what the output should be based on the guess
              while(player != currentPlayer)
              //The player can only guess if it is his turn
                   gameLock.lock();
                   try
                        otherPlayerTurn.await();
                   catch(InterruptedException e)
                        e.printStackTrace();
                   finally
                        gameLock.unlock();
              if(correctRange(guess))
              //If the guess is a valid guess
                   currentPlayer = (currentPlayer + 1) % 2;
                   //Switches player turn
                   players[currentPlayer].otherPlayerGuessed(guess);
                   gameLock.lock();
                   try
                        otherPlayerTurn.signal();
                        //Signals other player
                   finally
                        gameLock.unlock();
                   return true;
              else
                   return false;
         public boolean correctRange(int guess)
         //Tests for a valid guess between 0-10
              if(guess >= 0 && guess <= 10)
                   return true;
              else
                   return false;
         private class Player implements Runnable
         //Player class
              private Socket connection;
              private Scanner input;
              private Formatter output;
              private int playerNumber;
              private String mark;
              private boolean suspended = true;
              private boolean game = true;
              public Player(Socket socket, int number)
                   playerNumber = number;
                   mark = MARKS[playerNumber];
                   connection = socket;
                   try
                   //Tries to get the data streams
                        input = new Scanner(connection.getInputStream());
                        output = new Formatter(connection.getOutputStream());
                   catch(IOException e)
                        e.printStackTrace();
                        System.exit(1);
              public void otherPlayerGuessed(int guess)
              //Function that detemines whether the guess is too high/low or correct
                   if(guess == randomNumber)
                        output.format("Opponent guessed and won\n");
                        output.format("%d\n", guess);
                        output.flush();
                   else
                        output.format("Opponent guessed\n");
                        output.format("%d\n", guess);
                        output.flush();
              public void run()
              //The start of the threads, at the beginning messages go back and forth to set up the connection
              //and player names
                   try
                        displayMessage("Player " + mark + "connected \n");
                        output.format("%s\n", mark);
                        output.flush();
                        //Sends the message that the player has connected
                        if(playerNumber == PLAYER_1)
                             output.format("%s\n%s", "Player 1 connected ", "Waiting for another player\n");
                             output.flush();
                             gameLock.lock();
                             try
                                  while(suspended)
                                       otherPlayerConnected.await();
                                       //Waits for player 2
                             catch(InterruptedException e)
                                  e.printStackTrace();
                             finally
                                  gameLock.unlock();
                             output.format("Name1\n");
                             output.flush();     
                             p1Name = input.nextLine();
                             displayMessage("Player 1 = " + p1Name + "\n");
                             //Sends a message to enter the name and puts the received name
                             //in the variable p1Name
                             output.format("Other player connected. Your turn.\n");
                             output.flush();
                             //Starts the game when the other player has connected
                             //A lot of the turn base is done with message handling
                             //on the client side     
                        else
                             output.format("Name2\n");
                             output.flush();
                             p2Name = input.nextLine();
                             displayMessage("Player 2 = " + p2Name + "\n");
                             output.format("Player 2 connected. Please wait.\n");
                             output.flush();
                             //Sets up player 2's name and turn
                        while(game)
                        //while the game is not over
                             int guess = 0;
                             if(input.hasNext())
                                  guess = input.nextInt();
                             }//Gets next input
                             if(validateAndMove(guess, playerNumber))
                             //Sends the correct output based on the guess
                                  if(guess < randomNumber)
                                       if(playerNumber == 0)
                                            displayMessage(" \n"+p1Name+ " guess: " + guess);
                                       else
                                            displayMessage(" \n" p2Name " guess: " + guess);
                                       output.format("Guess too low.\n");
                                       output.flush();
                                  else if(guess > randomNumber)
                                       if(playerNumber == 0)
                                            displayMessage(" \n"+p1Name+ " guess: " + guess);
                                       else
                                            displayMessage(" \n" p2Name " guess: " + guess);
                                       output.format("Guess too high.\n");
                                       output.flush();
                                  else
                                       if(playerNumber == 0)
                                            displayMessage(" \n"+p1Name+ " guess: " + guess);
                                       else
                                            displayMessage(" \n" p2Name " guess: " + guess);
                                       output.format("You Win!\n");
                                       output.flush();
                                       game = false;
                                       //Ends game
                             else
                                  output.format("Invalid guess, try again\n");
                                  output.flush();
                   finally
                        try
                             connection.close();
                        catch(IOException e)
                             e.printStackTrace();
                             System.exit(1);
              }//End run
              public void setSuspended(boolean status)
                   suspended = status;
         }//End player class
    }//End Server class
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Thanks for the response
    I think I understand what you are saying, I just want to make sure I get it fully. I need to create a separate thread that runs just my connection process to make sure that the processes actually occur? If so, how would I go about doing this?
    Thanks again

  • Server/client IO ArrayList

    So, I have this client and server classes which work like that� Server just starts and waits for a client to connect, then the client �sends� a String which represents a username for that client. Server then stores the username in an ArrayList called usersList. It also stores the ObjectOutputStream(the server side ObjectOutputStream) of this connection in a HashMap called outStreamMap and then sends back to every connected client that ArrayList. The code is:
    Server:
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class Server{
    public HashMap<String,ObjectOutputStream> outStreamMap;
    public ArrayList<String> usersList;
    public Server(){
      usersList=new ArrayList<String>();
      outStreamMap=new HashMap<String,ObjectOutputStream>();
      CallReceiver cr=new CallReceiver();
    public static void main(String[] args){
      Server serv=new Server();
    class CallReceiver implements Runnable{
    ServerSocket serverSocket;
    public CallReceiver(){
      try{
       serverSocket=new ServerSocket(5432);
       Thread callReceiverThread=new Thread(this);
       callReceiverThread.start();
      }catch(IOException e){e.printStackTrace();}
    public void run(){
      while(true){
       try{
        Socket socket=serverSocket.accept();
        InputStream is=socket.getInputStream();
        OutputStream os=socket.getOutputStream();
        ObjectOutputStream objOutStr=new ObjectOutputStream(os);
        ObjectInputStream objInStr=new ObjectInputStream(is);
        Object obj=objInStr.readObject();//reads the username
        String username=(String)obj;
        usersList.add(username);//adds the user to the ArrayList
        outStreamMap.put(username,objOutStr);//adds the output stream to the Map
        for(String user:usersList){//sends the ArrayList to every user
           outStreamMap.get(user).writeObject(usersList);
           outStreamMap.get(user).flush();
           System.out.println("Sent ArrayList:"+usersList+" to:"+user);
       }catch(Exception e){
          e.printStackTrace();}
    }//end of CallReceiver
    }//end of server
    Client:
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class Client{
    public Client(){
      try{
       Socket socket=new Socket("127.0.0.1",5432);
       OutputStream outStr=socket.getOutputStream();
       InputStream inStr=socket.getInputStream();
       ObjectOutputStream objOutStr=new ObjectOutputStream(outStr);
       ObjectInputStream objInStr=new ObjectInputStream(inStr);
       objOutStr.writeObject("John");//sends a string representing a username
       objOutStr.flush();
       ArrayList userlist;
       while(true){
         Object obj=objInStr.readObject();//reads an object wich actually is an ArrayList
         userlist=(ArrayList)obj;
         System.out.println("ArrayList received: "+userlist);
      }catch(Exception e){e.printStackTrace();}
    public static void main(String[] args){
    Client cl=new Client();
    }The client all it does is just waiting for an ArrayList and then just prints it on the command line.
    Lets say for example that you run a client with username, john. You get on the command line something like:
    ArrayList received: [john]
    Then you connect a second client with username, george (the first client is still connected, offcourse).
    So, you get on the first client�s command line:
    ArrayList received: [john]
    And on the second client�s command line:
    ArrayList received:[john, george]
    And so it goes, if you connect another one you get on the first�s [john], on the second�s [john, george] and on the third�s [john, george, mike]. And this is the problem I cannot understand how this is happening since the server �sends� the exact same ArrayList object to all clients! Please someone more openeyed than me help me!!

    This is due to ObjectStream caching, instead of resending the data, it will only send a marker (as in 'object foo sent again'). It doesn't know that the contents of the object are changed.
    This is due to the fact that ObjectStreams aren't really supposed to be used this way, and this way if you're writing the same object many times, it'll save on the bandwidth (it'll send only the backreference).
    Look at the writeUnshared() method in ObjectOutputStream.

  • \\SERVER\Clients\Setup\setup.exe with Windows Vista Error

    I added the first Vista client to an SBS 2003, SP1 domain.  Until now, all clients were WinXP, SP2.  Office 2003 is installed on the XP clients, and the Vista client, which may not be pertinent to this problem.
    As is normal, "\\SERVER\Clients\Setup\setup.exe /s SERVER" is executed when a user logs on to any domain client.  On the Vista client, I always get the dialog -- regardless of the account privilege -- asking for permission to run Setup.exe.  It is annoying.  Occasionally, the Program Compatiblity Assistant will appear and advise there's a known compatiblity issue with Setup.exe.  It points to KB article 926505 for resolution.  The title of the KB is, "Windows Small Business Server 2003: Windows Vista and Outlook 2007 compatibility update."
    When I run the SBS2003SP1-KB926505-X86-ENU.EXE fix, I get the error:  "This update cannot be installed.  Either it is already installed as part of an existing service pack, or it requires a more recent service pack.  For more information, see the systems requirements on the download page."
    I installed Windows Server 2003 SP2 and run the KB926505 fix, but I get the same error  "This update cannot be installed.  Either it is already installed as part of an existing service pack" After a reboot of te SBS server the same  problem on the Vista client, I always get the dialog -- regardless of the account privilege -- asking for permission to run Setup.exe.  It is annoying.  Occasionally, the Program Compatiblity Assistant will appear and advise there's a known compatiblity issue with Setup.exe.  It points to KB article 926505 for resolution.
    The problem is Windows Vista Business, because all windows XP clients have no problem at all.

    PNP,
    You do not say whether if you accept the permission dialog whether the setup continues or not, but the short answer to the question revolves around UAC.
    Remember that EVERY user (except the actual Administrator account) has only Standard user rights regardless of group.  When a task that requires Admin rights is executed, one of three things will happen: 1) If you are THE Administrator, then your task will continue.  2) If you have Admin rights, you will be prompted that a process is trying to use elevated rights and ask for permission, or 3) If you are a Standard user, you will either be denied flatly or prompted to supply credentials.  Which of these happen depend on GPO settings, but the default is to prompt.
    In any event, I believe that this is what you are running into, and is one of the big feature improvements in Vista.  Yes, it can be a bit annoying (Try deleting an "All Users" icon from the Start Menu!) but is there to place one more barrier between virus and malware writers and your OS.
    If it's TOO annoying to bear, you can turn off UAC by going into your profile and disabling it. (It requires Admin rights, of course. )  It is not recommended as you do a very effective job or nutering the Vista Security Model by doing so.
    If it, of course, your choice.  we IT Admins have a lot more issues with this than the standard user, but for me, I gladly take the tradeoff because I worry a lot less about those few I HAVE to give Admin rights to.
    Good luck!

  • JMS Internal Error at Server Client Adapter!JMS Service is not started

    Hi
    Can any one tell me how to trouble shoot for following errors:
    Failed to Create Connection! Reason: Response from the server could not be reached.
    JMS Internal Error at Server Client Adapter!JMS Service is not started
    The following hosts could not be reached 143:223:221:10:50310
    We are trying to send the request from SONICMQ JMS to R/3 and trying to post the response to Sonic Queue. but we are facing some problems for JMS adapter .
    but in JMS sender and receiver adapter i gave different IP and port for listen the SONIC queue. why it is showing in different IP here? this message got from logviewer.
    regards
    Rambarki...

    Rambarki,
    What is the error displayed on the Adapter Monitoring pages?
    Generally the correct error descriptions for connectivity issues are found on adapter monitoring UI than any other.
    Other possible reasons could be :
    <i>JMS Service is not started
    The following hosts could not be reached 143:223:221:10:50310</i> This might be issue with your network settings i.e. XI server is unable to reach the specified IP on specified port.
    Regards,
    Amol

  • How to secure connection in sql server 2008? my main problem is which certificate should i add in mmc

    i'm recently working on hardening of sql server 2008. now i face with a problem. my problem is  how to secure connection in sql server 2008?  my main problem is which certificate should i add in mmc? what are these certificates about?and guide
    me in choosing the appropriate certificate.
    and how should i know that the connection in sql server is secured?
    plz guide me from the beginning cause i'm rookie in this subject.
    thanks in advance.

    Hi sqlfan,
    Question 1: my problem is how to secure connection in sql server 2008?
    Microsoft SQL Server can use Secure Sockets Layer (SSL) to encrypt data that is transmitted across a network between an instance of SQL Server and a client application. For more information about Encrypting Connections to SQL Server, please refer to the following
    article:
    http://technet.microsoft.com/en-us/library/ms189067(v=sql.105).aspx
    Question 2: my main problem is which certificate should i add in mmc? what are these certificates about?and guide me in choosing the appropriate certificate.
    To install a certificate in the Windows certificate store of the server computer, you will need to purchase/provision a certificate from a certificate authority first. So please go to a certificate authority to choose the appropriate certificate.
    For SQL Server to load a SSL certificate, the certificate must meet the following conditions:
    The certificate must be in either the local computer certificate store or the current user certificate store.
    The current system time must be after the Valid from property of the certificate and before the Valid to property of the certificate.
    The certificate must be meant for server authentication. This requires the Enhanced Key Usage property of the certificate to specify Server Authentication (1.3.6.1.5.5.7.3.1).
    The certificate must be created by using the KeySpec option of AT_KEYEXCHANGE. Usually, the certificate's key usage property (KEY_USAGE) will also include key encipherment (CERT_KEY_ENCIPHERMENT_KEY_USAGE).
    The Subject property of the certificate must indicate that the common name (CN) is the same as the host name or fully qualified domain name (FQDN) of the server computer. If SQL Server is running on a failover cluster, the common name must match the host
    name or FQDN of the virtual server and the certificates must be provisioned on all nodes in the failover cluster.
    Question 3: how should i know that the connection in sql server is secured?
    If the certificate is configured to be used, and the value of the ForceEncryption option is set to Yes, all data transmitted across a network between SQL Server and the client application will be encrypted using the certificate. For more detail about this,
    please refer to Configuring SSL for SQL Server in the following article:
    http://technet.microsoft.com/en-us/library/ms189067(v=sql.105).aspx
    If you have any question, please feel free to let me know.
    Regards,
    Donghui Li

  • Weblogic startup class: problem calling EJB's

    Has anyone ever experienced a problem in using a startup class (registered in weblogic.properties)
    and tried to lookup and use an EJB in the same application?
    Basically, I have a startup class which registers to receive messages from an
    MQ queue, and when it receives a message, it tries to do a lookup of a bean and
    use it, but I receive a 'NullPointerException'.
    I'm running Weblogic 5.1
    (I know that Weblogic 6.0 makes use of MessageDrivenBeans, but my app isn't using
    6 or EJB 2.0)
    Thanks...

    Can you post weblogic.log? Are you sure that EJB was deployed successfully.
    Also comment the PROVIDER_URL in initial context and see if that solves the problem
    Viresh Garg
    BEA Systems
    shaun wrote:
    The exception is simply a 'NullPointerException' coming from the startup class
    (I don't have the old log file or I would include the trace here.). Basically,
    when my startup class receives a call to the onMessage(...) method (from listening
    for messages), it looks up an EJB on the server, through the InitialContect class
    and gets a 'null' returned back, thereby throwing the NullPointerException.
    If anyone else is successful in having a startup class which can lookup and call
    an EJB within the same Weblogic server, please help.
    Thanks again....
    Viresh Garg <[email protected]> wrote:
    Can you post the exception stack trace? Also what exactly are you doing
    in startup class.
    Viresh Garg
    Principal Developer Relations Engineer
    BEA Systems
    Shaun wrote:
    Has anyone ever experienced a problem in using a startup class (registeredin weblogic.properties)
    and tried to lookup and use an EJB in the same application?
    Basically, I have a startup class which registers to receive messagesfrom an
    MQ queue, and when it receives a message, it tries to do a lookup ofa bean and
    use it, but I receive a 'NullPointerException'.
    I'm running Weblogic 5.1
    (I know that Weblogic 6.0 makes use of MessageDrivenBeans, but my appisn't using
    6 or EJB 2.0)
    Thanks...

Maybe you are looking for

  • How to disable F1 to F12 keys in Web Browser when SWF file is in focus

    Hi all, Im running / loading a swf file in IE. I want to disable the function keys ( F1- F12 keys) in IE as I have defined special functions for these keys in my swf / flash file.Im using a javascript code to do this and the javascript code is workin

  • PL/SQL Programming

    Hi " I Need Help" I am trying to call a java program from inside a PL/SQL block. I created a java class and compiled it and then loaded that class into ORACLE database using the following method. Step 1: CONNECT System/Manager GRANT CREATE ANY DIRECT

  • Problem locating files after migration from PC to Mac

    I have just migrated files from my PC to my Mac.  I have logged into the new user account but I finder is telling me there are no files located in the new user. It also doesnt appear that a "user" folder has been created for the new user which may be

  • CALLING BAPI in ABAP program

    Hi, I want to call BAPI_MATERIAL_AVAILABILITY in ABAP program. Please give me some sample code how i can do this??? Please help

  • Relationship in Business Partner repository.

    I need to do a relationship among the BP where each record in Main Table correspond a BP (Person or Organization). The relationship should link the BPs as shown below: Records 1; John 2; Mary 3; ACME In record 1, I need to say that John is married wi