Socket handling

Hi,
I need to implement a socket based application like this:
I need to build a server side that can handlle up to 9 clients.
Each client will send to the server raws data (every 4-6 raws are package) and the server has to take the data and make calculations with it.
My question is: how the server can search the clients sockets and take the data ?

The server can't search for clients. It just can wait for client connections. So, each client has to connect to the server and during connection, the server gets the message and can keep the client socket for later sending back the result.
                    logger.finest(serverSocket.getLocalPort() + " is waiting for client to connect ...");
                    Socket socket = serverSocket.accept(); //block until next client connected
                    logger.finest(serverSocket.getLocalPort() + " accepted connection of client '"+getAddress(socket, true)+"'");See All about Sockets

Similar Messages

  • Java Logging - Socket Handler

    How to use Socket Handler of java.util.logging package. Do we need to write a SocketServer to receive the LogRecord from SocketHandler or java itself provides SocketServer implementation to log the records?

    I am not seeing any socket server implementation just like log4j in java logging (JDK1.4.2) API documentation. I just want to know is there any additional packages available for this.

  • How to make a socket connection timeout infinity in Servlet doPost method.

    I want to redirect my System.out to a file on a remote server (running Apache Web Server and Apache Tomcat). For which I have created a file upload servlet.
    The connection is established only once with the servlet and the System.out is redirected to it. Everything goes fine if i keep sending data every 10 second.
    But it is required that the data can be sent to the servlet even after 1 or 2 days. The connection should remain open. I am getting java.net.SocketTimeoutException: Read timed out Exception as the socket timeout occurs.
    Can anyone guide me how to change the default timeout of the socket connection in my servlet class.
    Following is the coding to establish a connection with the Servlet.
    URL servletURL = new URL(mURL.getProtocol(), mURL.getHost(), port, getFileUploadServletName() );
    URLConnection mCon = servletURL.openConnection();
    mCon.setDoInput(true);
    mCon.setDoOutput(true);
    mCon.setUseCaches(false);
    mCon.setRequestProperty("Content-Type", "multipart/form-data");
    In the Servlet Code I am just trying to read the input from the in that is the input stream.
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    BufferedInputStream in = new BufferedInputStream(req.getInputStream());
    byte [] content = new byte[1024];
    do
    read = in.read(content, 0, content.length);
    if (read > 0)
    out.write(content, 0, read);
    I have redirected the System.out to the required position.
    System.setOut(........);
    Can anyone guide me how to change the default timeout of the socket connection in my servlet class.

    I am aware of the setKeepAlive() method, but this can only used with the sockets. Here i am inside a servlet, have access to HTTPServletRequest and HTTPServletResponse and I don't know how to get access to the underlying sockets as the socket handling will be handled by the tomcat itself. If I am right there will be method in the apache tomcat 6.0.x to set this property. But till now I am not getting it.

  • Sockets & inetd

    Hello!
    It all worked just fine before I used inetd to start the server. When I use inetd I get this exception:
    Network error: Address already in useSo, the inetd-stuff works, because the server is started, but...
    This is my code:
    Client:
    public class Client {
        private int port = 7654;
        private String host = "ausone";
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
        public Client (String host, int port) {
            this.host = host;
            this.port = port;
            setup ();
        private void setup () {
            try {
                Socket s = new Socket(host, port);
                System.out.println ( "Connected to: " +s.getInetAddress().getHostName() );
                out = new ObjectOutputStream (s.getOutputStream());
                in = new ObjectInputStream (s.getInputStream());
                } catch (IOException e) {
                    System.out.println ("Could not connect to socket: "+e);
    Server:
    public class Server {
        private ServerSocket server;
        public static final int DEFAULT_PORT = 7654;
        public static void main(String[] args) {
            Server tcserver = new Server();
            tcserver.runServer();
        private void runServer() {
            ServerThread newServerThread = null;
            Socket newSocket = null;
            try {
                server = new ServerSocket (DEFAULT_PORT);           //<------ Here!!
                while (true) {
                    System.out.println ("Waiting for client connection");
                    for(int i = 0; i < 10; i++) {
                        newSocket = server.accept ();
                        newServerThread = new ServerThread (newSocket,i);
                        newServerThread.start ();
            } catch (EOFException eofException) {
                System.out.println ("Client terminated the connection.");
            } catch (IOException ioException) {
                System.out.println ("Network error: " + ioException.getMessage());
        private class ServerThread extends Thread {
            Socket connection = null;
            private ObjectOutputStream out;
            private ObjectInputStream in;
            public ServerThread(Socket socket, int num) {
                connection = socket;
                out = new ObjectOutputStream (connection.getOutputStream());
                in = new ObjectInputStream (connection.getInputStream());
                //send client answer
                try {
                    String result = "testing";
                    out.writeObject (result);
                } catch (IOException e) {
                    System.out.println ("IO Error "+e);
    }So, what is wrong!!!
    And, another thing I noticed was that I can't use ObjectInputStream anymore, then I get a InvalideStreamHeader... or something like that.
    Please! I really need some help...

    Thanks for your answers, I'm sorry for my late reply.
    I have one more question for you Sylvia.
    Perhaps it's just me not knowing the best way to solv
    my problem, it's like this: Under my applet, I have
    native codes and libraries, I don't know if that makes
    it any different. The problem is that if two or more
    users connect to the server at the same time the
    server-code "crashes". So I need separate processes (I
    think), and I thought that using inetd was the way to
    do it. Otherwise, how will the server know to which
    user it will send the answer? Please correct me if I'm
    wrong!
    LinaLina, sounds like your native code is not thread safe. If fixing that is not an option, then you're probably right that you'll need separate processes. If you want to run things from inetd, then just skip all the socket handling stuff, and treat System.out as the OutputStream you would have got from the socket, and System.in as the InputStream you would have got.
    It's usual in such circumstances to provide a command line option that tells the program whether to listen on a socket first, or just go straight into processing the connection it gets from inetd. That makes development a lot easier.
    That said, starting a VM is very expensive, and each one takes a lot of memory. One possible alternative is to seperate out the native code into a seperate c/c++ program that can be invoked from the Java VM, and communicated with using sockets. How practical that is depends on the extent of the natiive API, and the frequency of calls to it.
    Sylvia.

  • SocketExceptopn: Socket Operation on nonsocket: JVM_Bind - what ?

    Hi,
    I'm a new Java-application developer. I'm stadying Java at university in Kassel (germany) an now in university holiday I wnat to development a little messanging tool. So I have tried some basic technics.... but the simplesed things won't work!
    I've wrote this code:
    import java.net.*;
    import java.io.*;
    class MulClient
    public static void main( String args[] ) throws IOException
    Socket server = new Socket("localhost", 450 );
    But if I complie the code an run it....the JVM throws an Exception:
    Exception in thread "main" java.net.SocketException: Socket operation on nonsocket: JVM_Bind
    at java.net.PlainSocketImpl.socketBind(Native Method)
    at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:359)
    at java.net.Socket.bind(Socket.java:553)
    at java.net.Socket.<init>(Socket.java:363)
    at java.net.Socket.<init>(Socket.java:178)
    at MulClient.main(MulClient.java:8)
    I'm using windows xp Sp1 an a firewall (kerio personal firewall), ie 6 sp1....I'm behind a router but protocolls such as TCP/ip are installed..of course....
    Excause me bad english.....
    Thanks!
    Faithfully MrSandman

    Hi,
    1) You haven't created a ServerSocket so nothing's
    listening on that port. I doubt this is it, as it
    would probabl time out.If I start the server class-file (changed port 1044):
    import java.net.*;
    import java.io.*;
    public class MulServer
      public static void main( String args[] ) throws IOException
        ServerSocket server = new ServerSocket( 1044 );
         while ( true )
          Socket client = server.accept();
          InputStream  in  = client.getInputStream();
          OutputStream out = client.getOutputStream();
          int start = in.read();
          int end = in.read();
          int result = start * end;
          out.write( result );
          client.close();
    }the same exception appears. So there can't be a server listining on that port. But why doesn't this work?
    on MS developers page the exception or winsocket error is explained:
    "An operation was attempted on something that is not a socket. Either the socket handle parameter did not reference a valid socket, or for select, a member of an fd_set was not valid."
    But I don't understand; what does this mean?
    2) There is a server/listener type dealy bound to
    that port, but it's a FIFO or named pipe or
    something, rather than a Socket.What? do you think there is another application running on that port. There isn't anyone.
    I can't believe. I've tried another network-sample file taken from an internet tutorial...(I thought...this should work...) but the same exception....
    Any ideas? Please help!
    Thanks MrSandman

  • TCP/Socket Qn

    We use ServerSocket.accept() on the server-side to get a communcation "end-point" between the server and the client. The object returned is a Socket object. We typically spawn a thread to handle subsequent communication between these 2 end-points using the returned Socket handle. The server will end up getting many Socket handle over time for servicing requests from clients:
    while (true) {
    Socket s=serverSocket.accept();
    new HandlerThread(s).start();
    In most cases, the communications between the end-points will be conducted using TCP packet. The TCP packet includes information like the address of the client and the server, the client port and the server port and some other checksum information. The question now is, for any incoming packet destined for this server (based on the port number), how does it know to arrive at a particular Socket handle?
    Ben

    This won't work if I run 2 applications on the client side. Eg, 2 ftp clients pointing to the same server.
    Rdgs,
    Ben

  • Override SSL handling in WS7 - JSSE/SSLContext/SSLSocketFactory - possible?

    Hi there,
    I'm currently trying to get SSL working with pre-shared keys, which is (as far as I know) currently not possible with SunJSSE (using JDK6). However OpenSSL supports PSKs and I already figured out that using OpenSSL for that purpose is possible - at least with Tomcat providing a custom libtcnative linked against a specific OpenSSL version. For additional options not covered by that solution it is even possible to specify ones own SSLImplementation in Tomcat's connector configuration.
    Never the less, I would like to use WS7 for that purpose but I did not find any documentation on replacing current SSL handling with a custom implementation - besides implementing my own JSSE provider.
    Is it possible to override the default SSL implementation used by WS7? And if not directly, are settings in java.security regarding default SSLSocketFactory honored or has WS7 its own philosophy about socket handling?
    Edit: Hmm, seems like pkcs11 functions from libnss are used for that purpose. Am I right? So no way to work around that issue in Java?
    Thanks in advance :)
    Kind Regards,
    Max
    Edited by: kazcor_ol on Jun 4, 2009 4:02 AM - libnss recognized

    Hi there,
    I'm currently trying to get SSL working with pre-shared keys, which is (as far as I know) currently not possible with SunJSSE (using JDK6). However OpenSSL supports PSKs and I already figured out that using OpenSSL for that purpose is possible - at least with Tomcat providing a custom libtcnative linked against a specific OpenSSL version. For additional options not covered by that solution it is even possible to specify ones own SSLImplementation in Tomcat's connector configuration.
    Never the less, I would like to use WS7 for that purpose but I did not find any documentation on replacing current SSL handling with a custom implementation - besides implementing my own JSSE provider.
    Is it possible to override the default SSL implementation used by WS7? And if not directly, are settings in java.security regarding default SSLSocketFactory honored or has WS7 its own philosophy about socket handling?
    Edit: Hmm, seems like pkcs11 functions from libnss are used for that purpose. Am I right? So no way to work around that issue in Java?
    Thanks in advance :)
    Kind Regards,
    Max
    Edited by: kazcor_ol on Jun 4, 2009 4:02 AM - libnss recognized

  • Wierdness with NIO socket on Solaris 2.10 part I I

    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.nio.channels.spi.SelectorProvider;
    import java.util.*;
    public class NioClient implements Runnable {
    private InetAddress hostAddress;
    private int port;
    private Selector selector;
    private ByteBuffer readBuffer = ByteBuffer.allocate(8192);
    private List pendingChanges = new LinkedList();
    private Map pendingData = new HashMap();
    private Map rspHandlers = Collections.synchronizedMap(new HashMap());
    public NioClient(InetAddress hostAddress, int port) throws IOException {
    this.hostAddress = hostAddress;
    this.port = port;
    this.selector = this.initSelector();
    public void send(byte[] data, RspHandler handler) throws IOException {
    SocketChannel socket = this.initiateConnection();
    this.rspHandlers.put(socket, handler);
    synchronized (this.pendingData) {
    List queue = (List) this.pendingData.get(socket);
    if (queue == null) {
    queue = new ArrayList();
    this.pendingData.put(socket, queue);
    queue.add(ByteBuffer.wrap(data));
    this.selector.wakeup();
    public void run() {
    while (true) {
    try {
    synchronized (this.pendingChanges) {
    Iterator changes = this.pendingChanges.iterator();
    while (changes.hasNext()) {
    ChangeRequest change = (ChangeRequest) changes.next();
    switch (change.type) {
    case ChangeRequest.CHANGEOPS:
    SelectionKey key = change.socket
    .keyFor(this.selector);
    key.interestOps(change.ops);
    break;
    case ChangeRequest.REGISTER:
    change.socket.register(this.selector, change.ops);
    break;
    this.pendingChanges.clear();
    this.selector.select();
    Iterator selectedKeys = this.selector.selectedKeys().iterator();
    while (selectedKeys.hasNext()) {
    SelectionKey key = (SelectionKey) selectedKeys.next();
    selectedKeys.remove();
    if (!key.isValid()) {
    continue;
    if (key.isConnectable()) {
    this.finishConnection(key);
    } else if (key.isReadable()) {
    this.read(key);
    } else if (key.isWritable()) {
    this.write(key);
    } catch (Exception e) {
    e.printStackTrace();
    private void read(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    this.readBuffer.clear();
    int numRead;
    try {
    numRead = socketChannel.read(this.readBuffer);
    } catch (IOException e) {
    key.cancel();
    socketChannel.close();
    return;
    if (numRead == -1) {
    key.channel().close();
    key.cancel();
    return;
    this.handleResponse(socketChannel, this.readBuffer.array(), numRead);
    private void handleResponse(SocketChannel socketChannel, byte[] data,
    int numRead) throws IOException {
    byte[] rspData = new byte[numRead];
    System.arraycopy(data, 0, rspData, 0, numRead);
    RspHandler handler = (RspHandler) this.rspHandlers.get(socketChannel);
    if (handler.handleResponse(rspData)) {
    socketChannel.close();
    socketChannel.keyFor(this.selector).cancel();
    private void write(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    synchronized (this.pendingData) {
    List queue = (List) this.pendingData.get(socketChannel);
    while (!queue.isEmpty()) {
    ByteBuffer buf = (ByteBuffer) queue.get(0);
    socketChannel.write(buf);
    if (buf.remaining() > 0) {
    break;
    queue.remove(0);
    if (queue.isEmpty()) {
    key.interestOps(SelectionKey.OP_READ);
    private void finishConnection(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    try {
    socketChannel.finishConnect();
    } catch (IOException e) {
    System.out.println(e);
    key.cancel();
    return;
    key.interestOps(SelectionKey.OP_WRITE);
    private SocketChannel initiateConnection() throws IOException {
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    socketChannel
    .connect(new InetSocketAddress(this.hostAddress, this.port));
    synchronized (this.pendingChanges) {
    this.pendingChanges.add(new ChangeRequest(socketChannel,
    ChangeRequest.REGISTER, SelectionKey.OP_CONNECT));
    return socketChannel;
    private Selector initSelector() throws IOException {
    return SelectorProvider.provider().openSelector();
    public static void main(String[] args) {
    try {
    System.out.println ("the host name is " + args[0]);
    NioClient client = new NioClient(
    InetAddress.getByName(args[0]), 4444);
    Thread t = new Thread(client);
    t.setDaemon(true);
    t.start();
    RspHandler handler = new RspHandler();
    client.send(
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><a><queryInstrument/></a>\n"
    .getBytes(), handler);
    handler.waitForResponse();
    } catch (Exception e) {
    e.printStackTrace();
    }Edited by: LuriRon on Mar 16, 2009 10:42 AM

    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.nio.channels.spi.SelectorProvider;
    import java.util.*;
    public class NioClient implements Runnable {
    private InetAddress hostAddress;
    private int port;
    private Selector selector;
    private ByteBuffer readBuffer = ByteBuffer.allocate(8192);
    private List pendingChanges = new LinkedList();
    private Map pendingData = new HashMap();
    private Map rspHandlers = Collections.synchronizedMap(new HashMap());
    public NioClient(InetAddress hostAddress, int port) throws IOException {
    this.hostAddress = hostAddress;
    this.port = port;
    this.selector = this.initSelector();
    public void send(byte[] data, RspHandler handler) throws IOException {
    SocketChannel socket = this.initiateConnection();
    this.rspHandlers.put(socket, handler);
    synchronized (this.pendingData) {
    List queue = (List) this.pendingData.get(socket);
    if (queue == null) {
    queue = new ArrayList();
    this.pendingData.put(socket, queue);
    queue.add(ByteBuffer.wrap(data));
    this.selector.wakeup();
    public void run() {
    while (true) {
    try {
    synchronized (this.pendingChanges) {
    Iterator changes = this.pendingChanges.iterator();
    while (changes.hasNext()) {
    ChangeRequest change = (ChangeRequest) changes.next();
    switch (change.type) {
    case ChangeRequest.CHANGEOPS:
    SelectionKey key = change.socket
    .keyFor(this.selector);
    key.interestOps(change.ops);
    break;
    case ChangeRequest.REGISTER:
    change.socket.register(this.selector, change.ops);
    break;
    this.pendingChanges.clear();
    this.selector.select();
    Iterator selectedKeys = this.selector.selectedKeys().iterator();
    while (selectedKeys.hasNext()) {
    SelectionKey key = (SelectionKey) selectedKeys.next();
    selectedKeys.remove();
    if (!key.isValid()) {
    continue;
    if (key.isConnectable()) {
    this.finishConnection(key);
    } else if (key.isReadable()) {
    this.read(key);
    } else if (key.isWritable()) {
    this.write(key);
    } catch (Exception e) {
    e.printStackTrace();
    private void read(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    this.readBuffer.clear();
    int numRead;
    try {
    numRead = socketChannel.read(this.readBuffer);
    } catch (IOException e) {
    key.cancel();
    socketChannel.close();
    return;
    if (numRead == -1) {
    key.channel().close();
    key.cancel();
    return;
    this.handleResponse(socketChannel, this.readBuffer.array(), numRead);
    private void handleResponse(SocketChannel socketChannel, byte[] data,
    int numRead) throws IOException {
    byte[] rspData = new byte[numRead];
    System.arraycopy(data, 0, rspData, 0, numRead);
    RspHandler handler = (RspHandler) this.rspHandlers.get(socketChannel);
    if (handler.handleResponse(rspData)) {
    socketChannel.close();
    socketChannel.keyFor(this.selector).cancel();
    private void write(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    synchronized (this.pendingData) {
    List queue = (List) this.pendingData.get(socketChannel);
    while (!queue.isEmpty()) {
    ByteBuffer buf = (ByteBuffer) queue.get(0);
    socketChannel.write(buf);
    if (buf.remaining() > 0) {
    break;
    queue.remove(0);
    if (queue.isEmpty()) {
    key.interestOps(SelectionKey.OP_READ);
    private void finishConnection(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    try {
    socketChannel.finishConnect();
    } catch (IOException e) {
    System.out.println(e);
    key.cancel();
    return;
    key.interestOps(SelectionKey.OP_WRITE);
    private SocketChannel initiateConnection() throws IOException {
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    socketChannel
    .connect(new InetSocketAddress(this.hostAddress, this.port));
    synchronized (this.pendingChanges) {
    this.pendingChanges.add(new ChangeRequest(socketChannel,
    ChangeRequest.REGISTER, SelectionKey.OP_CONNECT));
    return socketChannel;
    private Selector initSelector() throws IOException {
    return SelectorProvider.provider().openSelector();
    public static void main(String[] args) {
    try {
    System.out.println ("the host name is " + args[0]);
    NioClient client = new NioClient(
    InetAddress.getByName(args[0]), 4444);
    Thread t = new Thread(client);
    t.setDaemon(true);
    t.start();
    RspHandler handler = new RspHandler();
    client.send(
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><a><queryInstrument/></a>\n"
    .getBytes(), handler);
    handler.waitForResponse();
    } catch (Exception e) {
    e.printStackTrace();
    }Edited by: LuriRon on Mar 16, 2009 10:42 AM

  • Wierdness with NIO socket on Solaris 2.10 part I

    i tried the following NioClient and MockServer, and saw some weird behavior.
    1. If i run both the client and server on the same machine on Windows, the client connects to the server, queries the instrument and gets the list of instruments back.
    2. if i run both client and server on the same Solaris 2.10 box, the NioClient doesn't get anything back from the MockServer, not even an ACCEPT
    3. if i run the client and the server on different solaris 2.10 machines, they work fine.
    have anyone seen this before? can sometone sheds some lights?
    import java.net.*;
    import java.io.*;
    public class MockServer
         public static int counter = 2;
        public static void main(String[] args) throws IOException {
             int portNumber = Integer.parseInt(args[0]);
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(portNumber);
            } catch (IOException e) {
                System.err.println("Could not listen on port: " + portNumber);
                System.exit(1);
             System.out.println ("Listening on socket " + portNumber);
            do {             
                 Socket clientSocket = null;
                 try {
                     clientSocket = serverSocket.accept();
                     System.out.println ("starting a new client....");
                     MyThread mt = new MyThread (clientSocket);
                     mt.run ();
                 } catch (IOException e) {
                     System.err.println("Accept failed.");
                     System.exit(1);
            while (true);
    class MyThread
         private final Socket clientSocket;
         MyThread (Socket clientSocket)
              this.clientSocket = clientSocket;
         public void run ()
            new Thread (new Runnable () {
                     public void run ()
                          try
                               boolean instrumentquery = false;
                               PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                               BufferedReader in = new BufferedReader(
                                           new InputStreamReader(
                                           clientSocket.getInputStream()));
                               String inputLine;                          
                               String successoutputLine =
                                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><return><returncode>success</returncode><detail>everything is good</detail></return>";
                               String failoutputLine =
                                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><return><returncode>failure</returncode><detail>something is not good</detail></return>";
                               String instrumentsoutput =
                                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><instruments><instrument><contract>usg-505Y</contract><cusip>12131121</cusip><deactivated>false</deactivated><halted>false</halted></instrument><instrument><contract>usg-305Y</contract><cusip>121312342</cusip><deactivated>false</deactivated><halted>false</halted></instrument></instruments>";
                               while ((inputLine = in.readLine()) != null) {
                                    System.out.println ("Receiving the following" + inputLine);
                                    if (inputLine.contains("queryInstrument")) instrumentquery = true;
                                    if (inputLine.contains("</a>"))
                                         if (instrumentquery)
                                              instrumentquery = false;
                                              System.out.println ("Sending " + instrumentsoutput);
                                              out.println (instrumentsoutput);
                                         else
                                              if ((MockServer.counter % 2) == 0)
                                                   System.out.println ("Sending " + successoutputLine);
                                                   out.println(successoutputLine);
                                              else
                                                   System.out.println ("Sending " + failoutputLine);
                                                   out.println(failoutputLine);
                                              MockServer.counter++;
                               out.close();
                               in.close();
                               clientSocket.close();}
                          catch (Exception ex)
                 }).start (); }
    }please see topic "wierdness with NIO socket on Solaris 2.10 part II" for the NioClient code as the maximum per topic is 5000.

    code for NioClient.java
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.nio.channels.spi.SelectorProvider;
    import java.util.*;
    public class NioClient implements Runnable {
    private InetAddress hostAddress;
    private int port;
    private Selector selector;
    private ByteBuffer readBuffer = ByteBuffer.allocate(8192);
    private List pendingChanges = new LinkedList();
    private Map pendingData = new HashMap();
    private Map rspHandlers = Collections.synchronizedMap(new HashMap());
    public NioClient(InetAddress hostAddress, int port) throws IOException {
    this.hostAddress = hostAddress;
    this.port = port;
    this.selector = this.initSelector();
    public void send(byte[] data, RspHandler handler) throws IOException {
    SocketChannel socket = this.initiateConnection();
    this.rspHandlers.put(socket, handler);
    synchronized (this.pendingData) {
    List queue = (List) this.pendingData.get(socket);
    if (queue == null) {
    queue = new ArrayList();
    this.pendingData.put(socket, queue);
    queue.add(ByteBuffer.wrap(data));
    this.selector.wakeup();
    public void run() {
    while (true) {
    try {
    synchronized (this.pendingChanges) {
    Iterator changes = this.pendingChanges.iterator();
    while (changes.hasNext()) {
    ChangeRequest change = (ChangeRequest) changes.next();
    switch (change.type) {
    case ChangeRequest.CHANGEOPS:
    SelectionKey key = change.socket
    .keyFor(this.selector);
    key.interestOps(change.ops);
    break;
    case ChangeRequest.REGISTER:
    change.socket.register(this.selector, change.ops);
    break;
    this.pendingChanges.clear();
    this.selector.select();
    Iterator selectedKeys = this.selector.selectedKeys().iterator();
    while (selectedKeys.hasNext()) {
    SelectionKey key = (SelectionKey) selectedKeys.next();
    selectedKeys.remove();
    if (!key.isValid()) {
    continue;
    if (key.isConnectable()) {
    this.finishConnection(key);
    } else if (key.isReadable()) {
    this.read(key);
    } else if (key.isWritable()) {
    this.write(key);
    } catch (Exception e) {
    e.printStackTrace();
    private void read(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    this.readBuffer.clear();
    int numRead;
    try {
    numRead = socketChannel.read(this.readBuffer);
    } catch (IOException e) {
    key.cancel();
    socketChannel.close();
    return;
    if (numRead == -1) {
    key.channel().close();
    key.cancel();
    return;
    this.handleResponse(socketChannel, this.readBuffer.array(), numRead);
    private void handleResponse(SocketChannel socketChannel, byte[] data,
    int numRead) throws IOException {
    byte[] rspData = new byte[numRead];
    System.arraycopy(data, 0, rspData, 0, numRead);
    RspHandler handler = (RspHandler) this.rspHandlers.get(socketChannel);
    if (handler.handleResponse(rspData)) {
    socketChannel.close();
    socketChannel.keyFor(this.selector).cancel();
    private void write(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    synchronized (this.pendingData) {
    List queue = (List) this.pendingData.get(socketChannel);
    while (!queue.isEmpty()) {
    ByteBuffer buf = (ByteBuffer) queue.get(0);
    socketChannel.write(buf);
    if (buf.remaining() > 0) {
    break;
    queue.remove(0);
    if (queue.isEmpty()) {
    key.interestOps(SelectionKey.OP_READ);
    private void finishConnection(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    try {
    socketChannel.finishConnect();
    } catch (IOException e) {
    System.out.println(e);
    key.cancel();
    return;
    key.interestOps(SelectionKey.OP_WRITE);
    private SocketChannel initiateConnection() throws IOException {
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    socketChannel
    .connect(new InetSocketAddress(this.hostAddress, this.port));
    synchronized (this.pendingChanges) {
    this.pendingChanges.add(new ChangeRequest(socketChannel,
    ChangeRequest.REGISTER, SelectionKey.OP_CONNECT));
    return socketChannel;
    private Selector initSelector() throws IOException {
    return SelectorProvider.provider().openSelector();
    public static void main(String[] args) {
    try {
    System.out.println ("the host name is " + args[0]);
    NioClient client = new NioClient(
    InetAddress.getByName(args[0]), 4444);
    Thread t = new Thread(client);
    t.setDaemon(true);
    t.start();
    RspHandler handler = new RspHandler();
    client.send(
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><a><queryInstrument/></a>\n"
    .getBytes(), handler);
    handler.waitForResponse();
    } catch (Exception e) {
    e.printStackTrace();
    }

  • A single socket with a reader thread and a writer thread

    Could a socket handle reading and writing simultaneously? If it could, are there any impact?
    Thanks

    With a single socket, a client sent , for example, the first 10 IP packages and wait for the server acknowledge.TCP does that asynchronously from the application.
    If the server noticed that the 7th package was corrupted, then the client need to resend the 7th package.TCP does that asynchronously from the application.
    This could imply there were some idle times on both the client and server.Not at the client. TCP does all that asynchronously from the application. Data is written from the application into the socket send buffer and then the client continues execution. All the segmentation and packetization and acknowledgement and retry is asynchronous from the application. There is a delay at the server but's that's because all the data hasn't arrived, innit? so it's unavoidable. But in practice very few packets are lost and TCP runs at pretty much full speed all the time.
    You still haven't clarified whether you're talking about your code or TCP, but if you're not talking about what TCP does, you must be trying to build all this stuff into your application, which I've already spoken about as redundant at best and highly counter-productive at worst.
    If I open multiple sockets between the client and the server, these idle times would be minimize since the client , while waiting for the acknowledge, could send data to other sockets.This is fallacious for the reasons given above.

  • Socket leak

    I see some socket applications in my work, the client side applications usually don't bother to explicitly close the socket connection. TCP/IP doesn't specify that if a socket is not used for a long time, the socket will be closed automatically. i wonder if the client doesn't close the connection, will there be a resource leak? and will the server application hold the connection forever because the client neglects to notify it?

    The client side applications need fixing. This is a basic error. Yes there is a resource leak, several in fact: the Socket object, its input and output streams, any buffers associated with them, the socket handle, the kernel structures associated with the socket, the kernel socket send and receive buffers, ... and at the server side, all that plus either a Thread or a SelectionKey and whatever is attached to it.
    Socket.setKeepAlive(true) and Socket.setSoTimeout() should both be used at the server to defend against this sort of thing, but it shouldn't be permitted to enter the client application in the first place. What else don't they 'bother' to release? This is a major quality issue.

  • Error in installing CC&B 2.3.1 SP2

    Hi,
    I have CC&B 2.3.1 SP1 in my windows machine with Tomcat Server. I am trying to install SP2 but getting some error if i select some person or something in the control central. Installation didn't show up any error and server is staring up fine. Problem is CC&B is not loading any account or premise or any entity
    for example, I am getting below error if i select any account. SP1 was working fine and tried to install SP2 twice but same issue. Has anyone successfully installed SP2 in Tomcat ? Any suggestions would surely help. Thanks
    SYSUSER - 921196-109-1 2011-08-05 16:28:56,683 [http-6500-5] ERROR (cobol.host.OptimizedRemoteExecuterStub) An exception occurred invoking remote command.
    - 2011-08-05 16:28:56,684 [Log4j Socket Handler] INFO (log4j.net.SocketNode) Caught java.net.SocketException closing conneciton.
    SYSUSER - 921196-109-1 2011-08-05 16:28:56,684 [http-6500-5] INFO (cobol.host.RemoteJVMConnectionImpl) Connection to JVM 3 being shunned
    SYSUSER - 921196-109-1 2011-08-05 16:28:56,684 [http-6500-5] ERROR (cobol.host.RemoteJVMConnectionImpl) An exception has occurred calling the remote JVM
    SYSUSER - 921196-109-1 2011-08-05 16:28:56,684 [http-6500-5] ERROR (support.cobol.AbstractCobolProgram) An exception occurred calling cobol program CIPCACCP
    SYSUSER - 921196-109-1 2011-08-05 16:28:56,686 [http-6500-5] ERROR (api.service.ServiceExecutionPolicy) Rollback: Read failed
    SYSUSER - 921196-109-1 2011-08-05 16:28:56,686 [http-6500-5] ERROR (support.context.SessionExecutable) Caught exception from SessionExecutable.execute()
    SYSUSER - 921196-109-1 2011-08-05 16:28:56,687 [http-6500-5] ERROR (web.dataservlet.PageRead) Unexpected error.
    com.splwg.base.support.cobol.host.InputClosedException:
    The following stacked messages were reported as the LoggedException was rethrown:
    com.splwg.base.api.service.ServiceDispatcher$13.execute(ServiceDispatcher.java:552): Caught exception from SessionExecutable.execute()
    com.splwg.base.support.cobol.ServiceAdapter.invokePageService(ServiceAdapter.java:76): Rollback: Read failed
    com.splwg.base.support.cobol.host.CommandRunnerHolder.invoke(CommandRunnerHolder.java:31): An exception occurred calling cobol program CIPCACCP
    com.splwg.base.support.cobol.host.OptimizedRemoteExecuterStub.sendRequestGetResponse(OptimizedRemoteExecuterStub.java:83): An exception has occurred calling the remote JVM
    com.splwg.base.support.cobol.host.OptimizedRemoteExecuterStub.sendRequestGetResponse(OptimizedRemoteExecuterStub.java:83): An exception occurred invoking remote command.
    The root LoggedException was: The input was closed.
         at com.splwg.base.support.cobol.host.OptimizedObjectEncoder.readOptimized(OptimizedObjectEncoder.java:176)
         at com.splwg.base.support.cobol.host.OptimizedDataInput.readOptimized(OptimizedDataInput.java:41)
         at com.splwg.base.support.cobol.host.OptimizedObjectEncoder.readSerializable(OptimizedObjectEncoder.java:245)
         at com.splwg.base.support.cobol.host.OptimizedDataInput.readSerializable(OptimizedDataInput.java:49)
         at com.splwg.base.support.cobol.host.OptimizedRemoteExecuterStub.sendRequestGetResponse(OptimizedRemoteExecuterStub.java:83)
         at com.splwg.base.support.cobol.host.OptimizedRemoteExecuterStub.invoke(OptimizedRemoteExecuterStub.java:58)
         at com.splwg.base.support.cobol.host.RemoteRunnerImpl.invoke(RemoteRunnerImpl.java:111)
         at com.splwg.base.support.cobol.host.CommandRunnerHolder.invoke(CommandRunnerHolder.java:31)
         at com.splwg.base.support.cobol.AbstractCobolProgram$CallCobolClosure.run(AbstractCobolProgram.java:195)
         at com.splwg.base.support.interception.SessionInterceptionManager.notifyGenericCallStackJump(SessionInterceptionManager.java:268)
         at com.splwg.base.support.context.FrameworkSession.notifyGenericCallStackJump(FrameworkSession.java:1473)
         at com.splwg.base.support.cobol.AbstractCobolProgram$1.run(AbstractCobolProgram.java:115)
         at com.splwg.base.support.cobol.AbstractCobolProgram.callCobol(AbstractCobolProgram.java:125)
         at com.splwg.base.support.cobol.GenericCobolServiceProgram.callCobol(GenericCobolServiceProgram.java:64)
         at com.splwg.base.support.cobol.ServiceAdapter.invokePageService(ServiceAdapter.java:76)
         at com.splwg.base.support.service.cobol.CobolPageRereadHelper.read(CobolPageRereadHelper.java:34)
         at com.splwg.base.support.service.cobol.CobolPageReadService.read(CobolPageReadService.java:17)
         at com.splwg.base.support.service.PageReadService.privateExecute(PageReadService.java:56)
         at com.splwg.base.support.service.PageReadService.execute(PageReadService.java:39)
         at com.splwg.base.api.service.ServiceDispatcher.readItemInSession(ServiceDispatcher.java:627)
         at com.splwg.base.api.service.ServiceDispatcher$13.execute(ServiceDispatcher.java:553)
         at com.splwg.base.api.service.ServiceDispatcher$13.execute(ServiceDispatcher.java:552)
         at com.splwg.base.support.context.SessionExecutable.doInNewSession(SessionExecutable.java:39)
         at com.splwg.base.api.service.ServiceDispatcher.doInAppropriateSession(ServiceDispatcher.java:608)
         at com.splwg.base.api.service.ServiceDispatcher.readItem(ServiceDispatcher.java:558)
         at com.splwg.base.api.service.ServiceDispatcher.readItem(ServiceDispatcher.java:538)
         at com.splwg.serviceclient.LocalServiceDispatcher.read(LocalServiceDispatcher.java:129)
         at com.splwg.base.web.dataservlet.PageRead.service(PageRead.java:52)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
         at com.splwg.base.web.services.RequestContextFilter.doFilter(RequestContextFilter.java:50)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
         at com.splwg.base.web.utility.CompressionFilter.doFilter(CompressionFilter.java:46)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
         at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:525)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
         at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
         at java.lang.Thread.run(Thread.java:595)
    Caused by: java.io.EOFException
         at java.io.DataInputStream.readByte(DataInputStream.java:243)
         at com.splwg.base.support.cobol.host.OptimizedObjectEncoder.readOptimized(OptimizedObjectEncoder.java:75)
         ... 47 more
    - 2011-08-05 16:28:56,776 [JVM 3 ERROR logger] ERROR (cobol.host.ProcessLogger) Load error : file 'CIPCACCR'
    - 2011-08-05 16:28:56,877 [JVM 3 ERROR logger] ERROR (cobol.host.ProcessLogger) error code: 173, pc=0, call=1, seg=0
    - 2011-08-05 16:28:56,978 [JVM 3 ERROR logger] ERROR (cobol.host.ProcessLogger) 173 Called program file not found in drive/directory
    - 2011-08-05 16:28:57,079 [JVM 3 ERROR logger] ERROR (cobol.host.ProcessLogger)
    - 2011-08-05 16:28:57,246 [JVM 5 INFO logger] INFO (cobol.host.ProcessLogger) Remote JVM 5 started with arguments: 5 6505 6506 2
    - 2011-08-05 16:28:57,347 [JVM 5 INFO logger] INFO (cobol.host.ProcessLogger) INFO: Loaded spl.properties from classpath: {spl.runtime.cobol.sql.cursoredCache.maxRows=10, spl.tools.loaded.applications=base,ccb,cm, spl.runtime.cobol.sql.disableQueryCache=false, spl.runtime.utf8Database=true, spl.runtime.fusionlook=true, spl.runtime.cobol.encoding=UTF8, spl.runtime.cobol.sql.cache.maxTotalEntries=1000, spl.runtime.cobol.cobrcall=false, spl.runtime.cobol.sql.fetchSize=150, spl.runtime.environ.init.dir=C:/spl/CCB23/etc, spl.runtime.sql.highValue=?, spl.runtime.service.extraInstallationServices=CILTINCP, spl.runtime.oracle.statementCacheSize=300}
    - 2011-08-05 16:28:57,448 [JVM 5 INFO logger] INFO (cobol.host.ProcessLogger) - 2011-08-05 16:28:57,367 [Remote JVM:5 Main ] INFO (cobol.host.SocketStrategy) Socket strategy set to com.splwg.base.support.cobol.host.sockets.WindowsPipeSocketStrategy
    - 2011-08-05 16:28:57,549 [JVM 5 INFO logger] INFO (cobol.host.ProcessLogger) Remote JVM 5 listening for requests on port: 6506
    - 2011-08-05 16:28:58,094 [JVM 5 INFO logger] INFO (cobol.host.ProcessLogger) - 2011-08-05 16:28:58,094 [Remote JVM:5 Thread 1] INFO (cobol.host.CIPZMEMJ) CIPZMEMJ initialized successfully.
    - 2011-08-05 16:28:58,195 [JVM 5 INFO logger] INFO (cobol.host.ProcessLogger) INFO: Loaded spl.properties from classpath: {spl.runtime.cobol.sql.cursoredCache.maxRows=10, spl.tools.loaded.applications=base,ccb,cm, spl.runtime.cobol.sql.disableQueryCache=false, spl.runtime.utf8Database=true, spl.runtime.fusionlook=true, spl.runtime.cobol.encoding=UTF8, spl.runtime.cobol.sql.cache.maxTotalEntries=1000, spl.runtime.cobol.cobrcall=false, spl.runtime.cobol.sql.fetchSize=150, spl.runtime.environ.init.dir=C:/spl/CCB23/etc, spl.runtime.sql.highValue=?, spl.runtime.service.extraInstallationServices=CILTINCP, spl.runtime.oracle.statementCacheSize=300}
    - 2011-08-05 16:28:58,296 [JVM 5 INFO logger] INFO (cobol.host.ProcessLogger) INFO: Loaded log4j.properties from classpath: {log4j.logger.org.hibernate.type=debug, log4j.appender.A1.layout.ConversionPattern=%X{userId} - %X{transactionId} %d [%t] %-5p (%c{3}) %m%n, log4j.appender.A1.encoding=UTF-8, log4j.logger.spl.org.hibernate.SQL=info, log4j.logger.com.splwg=info, log4j.logger.spl.org.hibernate.type=info, log4j.logger.org.hibernate=info, log4j.logger.spl.com.splwg.base.support.hibernatetypes=info, log4j.appender.A1=org.apache.log4j.ConsoleAppender, log4j.appender.A1.layout=org.apache.log4j.PatternLayout, log4j.logger.org.hibernate.SQL=debug, log4j.logger.org.hibernate.cfg=warn, log4j.logger.com.splwg.base.support.hibernatetypes=debug, log4j.rootCategory=info, A1}
    - 2011-08-05 16:28:58,302 [Log4j Connection Listener] INFO (cobol.host.LocalLogServer) Connected to client at /10.143.9.188
    - 2011-08-05 16:28:58,305 [pool-2-thread-1] INFO (cobol.host.RotatingCommandRunnerProvider) All inflight requests have returned for JVM 3. Shutting it down.
    - 2011-08-05 16:28:58,381 [Remote JVM:5 Main ] INFO (cobol.host.RemoteJVM) Remote JVM 5 setup complete
    - 2011-08-05 16:28:59,306 [pool-2-thread-1] INFO (cobol.host.ProcessLogger) Shutting down JVM 3 INFO logger
    - 2011-08-05 16:28:59,306 [pool-2-thread-1] INFO (cobol.host.ProcessLogger) Shutting down JVM 3 ERROR logger

    hi
    I face a similar issue as u faced . Please let me know the solution .
    Error in Log file : When trying to switch language.
    ZOHAIB - 169696-23-1 2012-01-09 15:23:22,624 [[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'] ERROR (web.dataservlet.PageChange) Unexpected error.
    com.splwg.base.support.cobol.host.InputClosedException:
    The following stacked messages were reported as the LoggedException was rethrown:
    com.splwg.base.api.service.ServiceDispatcher$5.execute(ServiceDispatcher.java:248): Caught exception from SessionExecutable.execute()
    com.splwg.base.support.pagemaintenance.AbstractPageMaintenance.changeItem(AbstractPageMaintenance.java:134): Rollback: Change failed
    com.splwg.base.support.cobol.host.CommandRunnerHolder.invoke(CommandRunnerHolder.java:31): An exception occurred calling cobol program CIPZDATA
    com.splwg.base.support.cobol.host.OptimizedRemoteExecuterStub.sendRequestGetResponse(OptimizedRemoteExecuterStub.java:83): An exception has occurred calling the remote JVM
    com.splwg.base.support.cobol.host.OptimizedRemoteExecuterStub.sendRequestGetResponse(OptimizedRemoteExecuterStub.java:83): An exception occurred invoking remote command.

  • Cannot delete file on windows

    WE have an application. This application processes a list of files in a directory. Once it has processed, it is deleted. We are using the File.delete() API to delete the file. This application works fine on Unix, but when run on Windows, the delete method returns false status. It cannot delete the file and neither does it throw the exception. Is there any way to find out why this delete is failing. We have no clue.

    Maybe the file you get by the new operation
    tion doesn't exist.
    Pls check the return value of the
    the File.exists();.I can't believe that
    your code failed to delete the file if the return
    value is true.sudhirkd never said delete() returned true when it shouldn't have. Regarding exists(), it returns the value that matches the file's actual existence in the file system. Please run the following code on a Windows system to check for yourself:
            java.io.File file = new File ("temp.file");
            java.io.FileWriter out = new FileWriter (file);
            System.out.println ("file.delete() returns: " + file.delete ());
            System.out.println ("file exists: " + file.exists ());
            out.close (); // THIS IS THE IMPORTANT BIT
            System.out.println ("out closed");
            System.out.println ("file.delete() returns: " + file.delete ());
            System.out.println ("file exists: " + file.exists ());it will return something like this:
    file.delete() returns: false
    file exists: true
    out closed
    file.delete() returns: true
    file exists: false
    Once again, note that it is the explicit close() of the file writer that matters here, not running System.gc(). Relying on garbage collector is a sign of very immature implementation and unprofessional programming style. Java programmers need to be as careful about releasing resources as C/C++ programmers -- just because the heap memory is handled for you automatically does not mean you could ignore file handles, temp files, socket handles, etc.
    The example applies to Windows. Explicitly closing file handles is equally important on UNIX as well. For example, failure to do so and relying on GC may cause a JVM process to run out of file handles very quickly [default max is ~20 on Solaris unless you explicitly increase the soft porcess limits].
    Vlad.

  • End Of communication Error while executing java procedure (Urgent)

    Hi All,
    I am using oracle 10g on linux server. Client machine is on xp. I hava a java procedure which executes the sqlldr on server. Earlier it was working fine, but after reinstalling the oracle 10g on server. It started giving "end of Communication channel error". I am not aware that what paramete has to set. Can some body put light on this error.
    Bye
    Sachin

    This is the most frequently asked question from Oracle developers.. Never mind putting some light on this error, I want to put it alight! ;-)
    First thing. It is not The Error. It is a sympton of an error.
    This message does not come from the database. It comes from the client OCI (of JDBC) drivers - which suddenly discovered that the Oracle connection (usually a TCP socket connection) has been torn down at the server side. It attempts to write to that socket, only to find that the other party has hung up.
    Why has the other party hung up? That party is either a Dedicated Server Process or a Dispatcher Process. If a dedicated server dies (crashes), it will take its socket handles with it to The Great Recycle Bin In The Sky. If you was serviced by a shared server and it died, the Dispatcher (who handles the TCP comms for it), will automatically close that shared server's connection.
    Usually when a process dies on the Oracle server, it leaves behind an error in the alert log, and trace files. That is where you will find the inklings of what The Error was that caused your client to get the EOF on comms channel message.

  • Fatal NI connect error 12547/12170

    Hi,
    I am stakk with connection problem on customer Oracle server. Oracle database is installed on Microsoft Windows Server 2012 Standard. Version of Oracle DB is 11.2.0.4 Standard One Edition.
    Oracle database works fine on server. I had no problems/errors while installing (as admin). My user is memer of Local Admin Group. I am also able to connect to it with sqlplus (sqlplus username/password@tns_alias) and SQL Developer.
    Content of tnsnames, listener og sqlnet files are following:
    tnsnames.ora
    ORACLR_CONNECTION_DATA =
      (DESCRIPTION =
        (ADDRESS_LIST =  (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))   )
        (CONNECT_DATA =  (SID = CLRExtProc) (PRESENTATION = RO)  )  )
    SALES =
      (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.1.9)(PORT = 1521))
      (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = sales.company.se)))
    listener.ora
    SID_LIST_LISTENER =
      (SID_LIST =
        (SID_DESC =
          (SID_NAME = CLRExtProc) (ORACLE_HOME = D:\oracle\product\11.2.0\dbhome_1)
          (PROGRAM = extproc)  (ENVS = "EXTPROC_DLLS=ONLY:D:\oracle\product\11.2.0\dbhome_1\bin\oraclr11.dll") )  )
    LISTENER =
      (DESCRIPTION_LIST =
        (DESCRIPTION =      (ADDRESS = (PROTOCOL = TCP)(HOST = servername.company.se)(PORT = 1521))
                                          (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))))
    ADR_BASE_LISTENER = D:\oracle
    INBOUND_CONNECTION_TIMEOUT_LISTENER=180
    sqlnet.ora
    SQLNET.AUTHENTICATION_SERVICES= (NONE)
    SQLNET.INBOUND_CONNECT_TIMEOUT = 180
    ADR_BASE = D:\oracle\product\11.2.0\dbhome_1\log
    I am using VPN tunnel to connect to database from my client. I can ping server successfully. TNSPING to database works fine, but I am not able to connect to database. I get an error on client:
    ORA-12537 connection closed error.
    Alert log content is following:
    Fatal NI connect error 12547, connecting to:
    (LOCAL=NO)
      VERSION INFORMATION:
    TNS for 64-bit Windows: Version 11.2.0.4.0 - Production
    Oracle Bequeath NT Protocol Adapter for 64-bit Windows: Version 11.2.0.4.0 - Production
    Windows NT TCP/IP NT Protocol Adapter for 64-bit Windows: Version 11.2.0.4.0 - Production
      Time: 19-DEC-2013 13:01:47
      Tracing not turned on.
      Tns error struct:
        ns main err code: 12547
    TNS-12547: TNS:lost contact
        ns secondary err code: 12560
        nt main err code: 0
        nt secondary err code: 0
        nt OS err code: 0
    opiodr aborting process unknown ospid (88) as a result of ORA-609
    2013-12-19 13:05:28.990000 +01:00
    Fatal NI connect error 12170.
      VERSION INFORMATION:
    TNS for 64-bit Windows: Version 11.2.0.4.0 - Production
    Oracle Bequeath NT Protocol Adapter for 64-bit Windows: Version 11.2.0.4.0 - Production
    Windows NT TCP/IP NT Protocol Adapter for 64-bit Windows: Version 11.2.0.4.0 - Production
      Time: 19-DEC-2013 13:05:28
      Tracing not turned on.
      Tns error struct:
        ns main err code: 12535
    TNS-12535: TNS:operation timed out
        ns secondary err code: 12606
        nt main err code: 0
        nt secondary err code: 0
        nt OS err code: 0
      Client address: <unknown>
    opiodr aborting process unknown ospid (2384) as a result of ORA-609
    2013-12-19 13:44:44.855000 +01:00
    opiodr aborting process unknown ospid (1292) as a result of ORA-609
    2013-12-19 14:30:34.351000 +01:00
    I supposed that connection could use some more time so I set inbound_connection to 180 (3 minutes). Same error.
    Then I turn on support trace. Here is analyzed content:
    server_4424.trc
    Trying to get IP client address results in error. Host IP is not correct.
    [19-DEC-2013 13:42:35:692] nsgetclientaddress: Client address: "(ADDRESS=(PROTOCOL=tcp)(HOST=::1)(PORT=53749))"
    [19-DEC-2013 13:42:35:692] nsgetclientaddress: exit
    [19-DEC-2013 13:42:35:692] nszgclient: entry
    [19-DEC-2013 13:42:35:692] nszgclient: using dedicated context
    [19-DEC-2013 13:42:35:692] nazsgsnm: entry
    [19-DEC-2013 13:42:35:692] nau_genm: entry
    [19-DEC-2013 13:42:35:692] nau_genm: exit
    [19-DEC-2013 13:42:35:692] nazsgsnm: failed with error 12630
    [19-DEC-2013 13:42:35:692] nazsgsnm: exit
    [19-DEC-2013 13:42:35:692] nszgclient: returning no username
    [19-DEC-2013 13:42:35:692] nszgclient: returning no username
    [19-DEC-2013 13:42:35:692] nszgclient: exit
    [19-DEC-2013 13:42:35:692] nszgetuser: entry
    [19-DEC-2013 13:42:35:692] nszgetuser: using dedicated context
    [19-DEC-2013 13:42:35:692] nazsgunm: entry
    [19-DEC-2013 13:42:35:692] nau_gnm: entry
    [19-DEC-2013 13:42:35:692] nau_gnm: exit
    [19-DEC-2013 13:42:35:692] nazsgunm: failed with error 12630
    Getting package from client. And when reached to @ we get EOF (daflag=64)
    [19-DEC-2013 13:42:35:724] nttfprd: exit
    [19-DEC-2013 13:42:35:724] nsbasic_brc: type=6, plen=10
    [19-DEC-2013 13:42:35:724] nsbasic_brc: what=1, tot =10
    [19-DEC-2013 13:42:35:724] nsbasic_brc: packet dump
    [19-DEC-2013 13:42:35:724] nsbasic_brc: 00 0A 00 00 06 00 00 00  |........|
    [19-DEC-2013 13:42:35:724] nsbasic_brc: 00 40                    |.@      |
    [19-DEC-2013 13:42:35:724] nsbasic_brc: Got EOF (daflag=64).
    [19-DEC-2013 13:42:35:724] nserror: entry
    [19-DEC-2013 13:42:35:724] nsbasic_brc: exit: oln=0, dln=0, tot=10, rc=-1
    [19-DEC-2013 13:42:35:724] nioqer: entry
    [19-DEC-2013 13:42:35:724] nioqer:  incoming err = 12151
    [19-DEC-2013 13:42:35:724] nioqce: entry
    [19-DEC-2013 13:42:35:724] nioqce: exit
    [19-DEC-2013 13:42:35:724] nioqer:  returning err = 3113
    [19-DEC-2013 13:42:35:724] nioqer: exit
    [19-DEC-2013 13:42:35:724] nioqrc: exit
    [19-DEC-2013 13:42:35:724] nioqds: entry
    [19-DEC-2013 13:42:35:724] nioqds:  disconnecting...
    Handshake never succeded. Client was trying to read from transport but never succeeded. I assume it is because of wrong or non Client address: "(ADDRESS=(PROTOCOL=tcp)(HOST=::1)(PORT=53749))"
    [19-DEC-2013 13:41:43:803] nscon: doing connect handshake...
    [19-DEC-2013 13:41:43:803] nscon: recving a packet
    [19-DEC-2013 13:41:43:803] nsprecv: entry
    [19-DEC-2013 13:41:43:803] nsprecv: reading from transport...
    [19-DEC-2013 13:41:43:803] nttrd: entry
    [19-DEC-2013 13:44:44:855] nttrd: exit
    [19-DEC-2013 13:44:44:855] ntt2err: entry
    [19-DEC-2013 13:44:44:855] ntt2err: Read unexpected EOF ERROR on 2648
    [19-DEC-2013 13:44:44:855] ntt2err: exit
    [19-DEC-2013 13:44:44:855] nsprecv: error exit
    [19-DEC-2013 13:44:44:855] nserror: entry
    [19-DEC-2013 13:44:44:855] nserror: nsres: id=0, op=68, ns=12535, ns2=12606; nt[0]=0, nt[1]=0, nt[2]=0; ora[0]=0, ora[1]=0, ora[2]=0
    [19-DEC-2013 13:44:44:855] nscon: error exit
    [19-DEC-2013 13:44:44:855] nsdo: nsctxrnk=0
    [19-DEC-2013 13:44:44:855] nsdo: error exit
    [19-DEC-2013 13:44:44:855] nsinh_hoff: error recving request
    [19-DEC-2013 13:44:44:855] nsclose: entry
    [19-DEC-2013 13:44:44:855] nsvntx_dei: entry
    [19-DEC-2013 13:44:44:855] nsvntx_dei: exit
    [19-DEC-2013 13:44:44:855] nstimarmed: entry
    [19-DEC-2013 13:44:44:855] nstimarmed: no timer allocated
    [19-DEC-2013 13:44:44:855] nstimarmed: normal exit
    [19-DEC-2013 13:44:44:855] nstoClearTimeout: entry
    [19-DEC-2013 13:44:44:855] nstoClearTimeout: ATO disabled for ctx=0x000000001812ED30
    [19-DEC-2013 13:44:44:855] nstoClearTimeout: STO disabled for ctx=0x000000001812ED30
    [19-DEC-2013 13:44:44:855] nstoClearTimeout: RTO disabled for ctx=0x000000001812ED30
    [19-DEC-2013 13:44:44:855] nstoClearTimeout: PITO disabled for ctx=0x000000001812ED30
    [19-DEC-2013 13:44:44:855] nstoUpdateActive: entry
    [19-DEC-2013 13:44:44:855] nstoUpdateActive: Active timeout is -1 (see nstotyp)
    [19-DEC-2013 13:44:44:855] nstoDestroyAlarm: entry
    [19-DEC-2013 13:44:44:855] nstoDestroyAlarm: exit (0)
    [19-DEC-2013 13:44:44:855] nttctl: entry
    [19-DEC-2013 13:44:44:855] ntt2err: entry
    [19-DEC-2013 13:44:44:855] ntt2err: soc -1 error - operation=7, ntresnt[0]=530, ntresnt[1]=38, ntresnt[2]=0
    [19-DEC-2013 13:44:44:855] ntt2err: exit
    [19-DEC-2013 13:44:44:855] nttctl: entry
    [19-DEC-2013 13:44:44:855] ntt2err: entry
    [19-DEC-2013 13:44:44:855] ntt2err: soc -1 error - operation=7, ntresnt[0]=530, ntresnt[1]=38, ntresnt[2]=0
    [19-DEC-2013 13:44:44:855] ntt2err: exit
    [19-DEC-2013 13:44:44:855] nsfull_cls: entry
    [19-DEC-2013 13:44:44:855] nsfull_cls: cid=0, opcode=65, *bl=0, *what=0, uflgs=0x0, cflgs=0x40
    [19-DEC-2013 13:44:44:855] nsfull_cls: nsctx: state=1, flg=0x4000, mvd=0
    [19-DEC-2013 13:44:44:855] nsbfr: entry
    After 180 sec Oracle net sends following message:
    [19-DEC-2013 13:44:44:855] nsclose: normal exit
    [19-DEC-2013 13:44:44:855] nserror: entry
    [19-DEC-2013 13:44:44:855] nserror: nsres: id=0, op=73, ns=12535, ns2=12606; nt[0]=0, nt[1]=0, nt[2]=0; ora[0]=0, ora[1]=0, ora[2]=0
    [19-DEC-2013 13:44:44:855] nsinherit: error exit
    [19-DEC-2013 13:44:44:855] nioqper:  error from nsinherit: failed...
    [19-DEC-2013 13:44:44:855] nioqper:    ns main err code: 12535
    [19-DEC-2013 13:44:44:855] nioqper:    ns (2)  err code: 12606
    [19-DEC-2013 13:44:44:855] nioqper:    nt main err code: 0
    [19-DEC-2013 13:44:44:855] nioqper:    nt (2)  err code: 0
    [19-DEC-2013 13:44:44:855] nioqper:    nt OS   err code: 0
    [19-DEC-2013 13:44:44:855] niotns: No broken-connection function available.
    [19-DEC-2013 13:44:44:855] niomapnserror: entry
    [19-DEC-2013 13:44:44:855] niqme: entry
    [19-DEC-2013 13:44:44:855] niqme: reporting NS-12535 error as ORA-12535
    [19-DEC-2013 13:44:44:855] niqme: exit
    [19-DEC-2013 13:44:44:855] niomapnserror: exit
    [19-DEC-2013 13:44:44:855] niotns: Couldn't connect, returning 12170
    [19-DEC-2013 13:44:44:855] nioqer: entry
    [19-DEC-2013 13:44:44:855] nioqer:  incoming err = 12170
    [19-DEC-2013 13:44:44:855] nioqce: entry
    [19-DEC-2013 13:44:44:855] nioqce: exit
    [19-DEC-2013 13:44:44:855] nioqer:  returning err = 3136
    Firewall is off on Server. Network administrator says that there is no rules which could compromise communication/traffic on port 1521. I tried trcroute too and I get following conntent
    1     27ms      22 ms     17ms       192.168.97.1
    2      *         *        *          request aborted
    3     20 ms     18 ms     18 ms      server.company.se (192.168.1.9)
    Any suggestion, help or comments would be appriciated. I am running out of ideas.
    Tnx a lot,
    adi

    The error could be due to a port change/reconnect/redirect that fails.
    The problem: Listener.exe is a separate physical process image in the kernel as the Oracle.exe process. The Listener needs to start an Oracle dedicated server process (created by the Listener as a remote thread in the oracle.exe process). Then it needs to pass the socket handle (created when the Listener accepted the tcp connection of the client) to this thread in another physical process - in order for that thread to continue tcp comms with the client.
    This is not by default supported in Windows as I understand (always wrote a single threaded exe myself with the main thread acting as listener and child threads as dealing with client sessions, when developing Win32 tcp servers).
    On Unix/Linux it is fairly common  to pass the socket handle as stdin and stdout to a forked child process (a separate physical process).
    If the socket handle cannot be passed from the listener.exe to oracle.exe, then the oracle.exe thread could open a private port as tcp listening end-point and inform, via the Listener, the client to reconnect to that tcp port (i.e. SQL*Net on client gets a redirect).
    You will need to determine whether this is happening - as it would explain the initial successful tcp connect from client to Listener, followed by the tcp connection failing to the Oracle dedicated server process.
    Not sure how one checks on Windows - have last done Oracle on Windows back with Oracle 7.1. But I think there are support notes on this.
    I would use netstat myself on Linux/Unix - and list the ports used by client and server for the connection, and determine if a private/dynamic port was used to continue the client-server tcp communication as a renegotiated tcp session. netstat is also available on Windows and can be used in a similar fashion too.

Maybe you are looking for