Doubt on Multithreading socket server

Iam implemented a multi threaded socket server,My server is going to get the data from the client thro BufferedInputStream and then send back the same data to the originated client.If single client is running means no problem but if more than a client get connected with the server means data frm the client1 is sended to the client2 while client2 data comes to the client1.Iam using buffered output stream for writing data to the client.Iam declared both bufferedoutput and bufferedinput streams as public......... can anyone give the solution for the problem...its very urgen.... can any one do.......

class ServerSocketDemo
Lock lo=new ReentrantLock();
Condition con=lo.newCondition();
ServerSocket s;
Socket socket;
void runServer()
new Thread(new timeStampDemo(lo)).start();
s=new ServerSocket(9098);
for(;;)
new Thread(new ThreadParent(s.accept(),lo,con)).start();
class ThreadParent
Thread[] t;
Lock lo;
Condition con;
ThreadParent(Socket soc,Lock l,Condition c)
InputStream,OutputStream are created here using socket....
lo=l;
con=c;
public void run()
for(int i=0;i<2;i++)
t=new Thread(new ServerThread(OutputStream,lo,con));
t[i[.start();
for(;;)
using InputStream read the data....
then acquire the lock and then adding the data to linkedlist...
after adding the data it wil signal to serverthread....
class ServerThread implements Runnable
ServerThread(OutputStream,Lock l,Condition c)
assign all those to corresponding variables....
public void run()
for(;;)
when ever the parent thread signals
check the linkedlist...
if the length of the linked list greater than one means retrive the data and using that OutputStream send to corresponding user....
else it waits on condition variable
class timeStampDemo
timeStampDemo(Lock l)
assign this lock to corresponding variable...
public void run()
for(;;){
The lock variable should be used at certain stage for some period during that time all the process in the server should waits... after the ending of process it releases the lock then the server continues the function..........
The problem is iam using lock as globally... By implementing the server in that way means i got the same problem... for multiple client,one client data send to another client and vice versa.....if i am using the lock globally in the Parent thread then i wil pass to the Server Thread means it works normally.... But my specification is to compulsorly use the lock before accepting the connection..........

Similar Messages

  • Design question for database connection in multithreaded socket-server

    Dear community,
    I am programming a multithreaded socket server. The server creates a new thread for each connection.
    The threads and several objects witch are instanced by each thread have to access database-connectivity. Therefore I implemented factory class which administer database connection in a pool. At this point I have a design question.
    How should I access the connections from the threads? There are two options:
    a) Should I implement in my server class a new method like "getDatabaseConnection" which calls the factory class and returns a pooled connection to the database? In this case each object has to know the server-object and have to call this method in order to get a database connection. That could become very complex as I have to safe a instance of the server object in each object ...
    b) Should I develop a static method in my factory class so that each thread could get a database connection by calling the static method of the factory?
    Thank you very much for your answer!
    Kind regards,
    Dak
    Message was edited by:
    dakger

    So your suggestion is to use a static method from a
    central class. But those static-methods are not realy
    object oriented, are they?There's only one static method, and that's getInstance
    If I use singleton pattern, I only create one
    instance of the database pooling class in order to
    cionfigure it (driver, access data to database and so
    on). The threads use than a static method of this
    class to get database connection?They use a static method to get the pool instance, getConnection is not static.
    Kaj

  • Bean as Socket Server

    Is it possible to make a Bean like stand alone multithread socket server for normal client applications that uses TCP/IP sockets to communicate with server?
    I have read some docs and found only how to write EJB for clients written specially to communicate with bean (not normal sockets).
    My attemption to create ServerSocket directly from has failed cause of "java.security.AccessControlException: access denied (java.net.SocketPermission localhost:61 listen,resolve)". By i guess even it not failed it wont work cause ("The enterprise bean must not attempt to start [...] a thread" - EJB 2.1 spec).

    You can if you use the connector architecture. See the following for sample code, etc
    http://java.sun.com/developer/codesamples/connect.html
    http://developers.sun.com/prodtech/appserver/reference/techart/resource_adapters.html
    http://developers.sun.com/sw/building/tech_articles/j2ee_soap_part2.html

  • File Based Multithreaded Web Server Question

    Hi friends,
    I have the code of a simple File Based Multithreaded Web Server. I have been asked to add proper http/1.1 Keep-Alive behavior to it. As far as I understand it means to use the same socket for the request coming from the same client without opening a new socket for every request by it. I am unable to implement it. Any help would be greatly appreciated. The entire code is as below:
    package multithreadedwebserver.com;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    /** This Class declares the general and HTTP constants
    * and defines general static methods:
    class Constants {
    /** 2XX: generally "OK" */
    public static final int HTTP_OK = 200;
    public static final int HTTP_CREATED = 201;
    public static final int HTTP_ACCEPTED = 202;
    public static final int HTTP_NOT_AUTHORITATIVE = 203;
    public static final int HTTP_NO_CONTENT = 204;
    public static final int HTTP_RESET = 205;
    public static final int HTTP_PARTIAL = 206;
    /** 3XX: relocation/redirect */
    public static final int HTTP_MULT_CHOICE = 300;
    public static final int HTTP_MOVED_PERM = 301;
    public static final int HTTP_MOVED_TEMP = 302;
    public static final int HTTP_SEE_OTHER = 303;
    public static final int HTTP_NOT_MODIFIED = 304;
    public static final int HTTP_USE_PROXY = 305;
    /** 4XX: client error */
    public static final int HTTP_BAD_REQUEST = 400;
    public static final int HTTP_UNAUTHORIZED = 401;
    public static final int HTTP_PAYMENT_REQUIRED = 402;
    public static final int HTTP_FORBIDDEN = 403;
    public static final int HTTP_NOT_FOUND = 404;
    public static final int HTTP_BAD_METHOD = 405;
    public static final int HTTP_NOT_ACCEPTABLE = 406;
    public static final int HTTP_PROXY_AUTH = 407;
    public static final int HTTP_CLIENT_TIMEOUT = 408;
    public static final int HTTP_CONFLICT = 409;
    public static final int HTTP_GONE = 410;
    public static final int HTTP_LENGTH_REQUIRED = 411;
    public static final int HTTP_PRECON_FAILED = 412;
    public static final int HTTP_ENTITY_TOO_LARGE = 413;
    public static final int HTTP_REQ_TOO_LONG = 414;
    public static final int HTTP_UNSUPPORTED_TYPE = 415;
    /** 5XX: server error */
    public static final int HTTP_SERVER_ERROR = 500;
    public static final int HTTP_INTERNAL_ERROR = 501;
    public static final int HTTP_BAD_GATEWAY = 502;
    public static final int HTTP_UNAVAILABLE = 503;
    public static final int HTTP_GATEWAY_TIMEOUT = 504;
    public static final int HTTP_VERSION = 505;
    /* the Web server's virtual root directory */
    public static File root;
    static PrintStream log = null;
    /* Configuration information of the Web server is present
    * in this props object
    protected static Properties props = new Properties();
    /* timeout on client connections */
    static int timeout = 0;
    /* maximum number of worker threads */
    static int workerThreads = 5;
    /* General method for printing strings */
    static void printString(String s) {
    System.out.println(s);
    /* print logs to the log file */
    static void log(String s) {
    synchronized (log) {
    log.println(s);
    log.flush();
    /* print to the log file */
    static void printProperties() { 
    printString("\n");
    printString("#####################################################################");
    printString("\n");
    printString("Web server's virtual root directory= "+root);
    printString("Timeout on client connections in milliseconds= "+timeout);
    printString("Number of Worker Threads= "+workerThreads);
    printString("\n");
    printString("#####################################################################");
    printString("\n\n");
    printString("********************WEBSERVER STARTED SUCCESSFULLY********************\n");
    /* load server.properties from java.home */
    static void loadServerConfigurationProperties() throws IOException {
    File f = new File(System.getProperty("java.home")+"\\lib\\"+"server.properties");
    if (f.exists()) {
    InputStream is =new BufferedInputStream(new FileInputStream(f));
    props.load(is);
    is.close();
    String r = props.getProperty("root");
    if (r != null) {
    root = new File(r);
    if (!root.exists()) {
    throw new Error(root + " Server Root Directory does not exist");
    r = props.getProperty("timeout");
    if (r != null) {
    timeout = Integer.parseInt(r);
    r = props.getProperty("workerThreads");
    if (r != null) {
    workerThreads = Integer.parseInt(r);
    r = props.getProperty("log");
    if (r != null) {
    log = new PrintStream(new BufferedOutputStream(
    new FileOutputStream(r)));
    /* Assign default values to root, timeout,
    * workerThreads and log if the same have
    * not been specified in the server.propwerties file
    if (root == null) {   
    root = new File(System.getProperty("user.dir"));
    if (timeout <= 1000) {
    timeout = 5000;
    if (workerThreads > 25) {
    printString("\n");
    printString("#####################################################################");
    printString("\n");
    printString("Too many Threads!!!Maximum number of Worker Threads can be 15 only");
    printString("\n");
    printString("#####################################################################");
    workerThreads = 15;
    if (log == null) {
    log = System.out;
    public class WebServer extends Constants {
    /* Specifying Default port for listening the requests */
    static int port = 8080;
    /* The Vector class implements a growable array of objects.
    * Like an array, it contains components that can be accessed using an integer index.
    * The size of a Vector can grow or shrink as needed to accommodate adding and
    * removing items after the Vector has been created.
    * The workerThreads are added to the Vector object threads where the worker threads stand idle
    * Vector is used since it is synchronized
    static Vector threads = new Vector();
    public static void main(String[] userSpecifiedPort) throws Exception {
    if (userSpecifiedPort.length > 0) {
    port = Integer.parseInt(userSpecifiedPort[0]);
    loadServerConfigurationProperties();
    printProperties();
    /* Instantiate ThreadPoool class and call
    * the createThreadPool() method on threadPool object
    ThreadPool threadPool= new ThreadPool();
    threadPool.createThreadPool();
    /* This class implements java.lang.Runnable.
    * It runs in a worker thread to process the request and serve files to the clients.
    class Worker extends WebServer implements Runnable {
    static final byte[] EOL = {(byte)'\r', (byte)'\n' };
    final static int BUFFER_SIZE = 2048;
    /* A byte array buffer to read and write files.
    * Memory is allocated to it once in the construtor of the class Worker
    * and reused thereafter
    byte[] buffer;
    /* Socket for the client being handled */
    private Socket socket;
    Worker() {
    buffer = new byte[BUFFER_SIZE];
    socket = null;
    synchronized void setSocket(Socket socket) {
    this.socket = socket;
    notify();
    public synchronized void run() {
    do {
    if (socket == null) {
    /* Wait */
    try {
    wait();
    } catch (InterruptedException e) {
    continue;
    try {
    handleClientRequest();
    } catch (Exception e) {
    e.printStackTrace();
    socket = null;
    Vector pool = WebServer.threads;
    synchronized (pool) {
    /* When the request is complete add the worker thread back
    * into the pool
    pool.addElement(this);
    }while(true);
    void handleClientRequest() throws IOException {
    InputStream is = new BufferedInputStream(socket.getInputStream());
    PrintStream ps = new PrintStream(socket.getOutputStream());
    /* we will only block in read for this many milliseconds
    * before we fail with java.io.InterruptedIOException,
    * at which point we will abandon the connection.
    socket.setSoTimeout(WebServer.timeout);
    socket.setTcpNoDelay(true);
    /* Refresh the buffer from last time */
    for (int i = 0; i < BUFFER_SIZE; i++) {
    buffer[i] = 0;
    try {
    /* We will only support HTTP GET/HEAD */
    int readBuffer = 0, r = 0;
    boolean endOfLine=false;
    while (readBuffer < BUFFER_SIZE) {
    r = is.read(buffer, readBuffer, BUFFER_SIZE - readBuffer);
    if (r == -1) {
    /* EOF */
    return;
    int i = readBuffer;
    readBuffer += r;
    for (; i < readBuffer; i++) {
    if (buffer[i] == (byte)'\n' || buffer[i] == (byte)'\r') {
    /* read one line */
    endOfLine=true;
    break;
    if (endOfLine)
    break;
    /*Checking for a GET or a HEAD */
    boolean doingGet;
    /* beginning of file name */
    int index;
    if (buffer[0] == (byte)'G' &&
    buffer[1] == (byte)'E' &&
    buffer[2] == (byte)'T' &&
    buffer[3] == (byte)' ') {
    doingGet = true;
    index = 4;
    } else if (buffer[0] == (byte)'H' &&
    buffer[1] == (byte)'E' &&
    buffer[2] == (byte)'A' &&
    buffer[3] == (byte)'D' &&
    buffer[4] == (byte)' ') {
    doingGet = false;
    index = 5;
    } else {
    /* This method is not supported */
    ps.print("HTTP/1.0 " + HTTP_BAD_METHOD +
    " unsupported method type: ");
    ps.write(buffer, 0, 5);
    ps.write(EOL);
    ps.flush();
    socket.close();
    return;
    int i = 0;
    /* find the file name, from:
    * GET /ATG/DAS6.3.0/J2EE-AppClients/index.html HTTP/1.0
    * extract "/ATG/DAS6.3.0/J2EE-AppClients/index.html "
    for (i = index; i < readBuffer; i++) {
    if (buffer[i] == (byte)' ') {
    break;
    String filename = (new String(buffer, 0, index,
    i-index)).replace('/', File.separatorChar);
    if (filename.startsWith(File.separator)) {
    filename = filename.substring(1);
    File targ = new File(WebServer.root, filename);
    if (targ.isDirectory()) {
    File ind = new File(targ, "index.html");
    if (ind.exists()) {
    targ = ind;
    boolean fileFound = printHeaders(targ, ps);
    if (doingGet) {
    if (fileFound) {
    sendResponseFile(targ, ps);
    } else {
    fileNotFound(targ, ps);
    } finally {  
    // socket.close();
    System.out.println("Connection Close nahi kiya");
    boolean printHeaders(File targ, PrintStream ps) throws IOException {
    boolean ret = false;
    int responseStatusCode = 0;
    if (!targ.exists()) {
    responseStatusCode = HTTP_NOT_FOUND;
    ps.print("HTTP/1.0 " + HTTP_NOT_FOUND + " not found");
    ps.write(EOL);
    ret = false;
    } else {
    responseStatusCode = HTTP_OK;
    ps.print("HTTP/1.0 " + HTTP_OK+" OK");
    ps.write(EOL);
    ret = true;
    log("From " socket.getInetAddress().getHostAddress()": GET " +
    targ.getAbsolutePath()+"-->"+responseStatusCode);
    ps.print("Server: Simple java");
    ps.write(EOL);
    ps.print("Date: " + (new Date()));
    ps.write(EOL);
    if (ret) {
    if (!targ.isDirectory()) {
    ps.print("Content-length: "+targ.length());
    ps.write(EOL);
    ps.print("Last Modified: " + (new
    Date(targ.lastModified())));
    ps.write(EOL);
    String name = targ.getName();
    int ind = name.lastIndexOf('.');
    String ct = null;
    if (ind > 0) {
    ct = (String) map.get(name.substring(ind));
    if (ct == null) {
    ct = "unknown/unknown";
    ps.print("Content-type: " + ct);
    ps.write(EOL);
    } else {
    ps.print("Content-type: text/html");
    ps.write(EOL);
    return ret;
    void fileNotFound(File targ, PrintStream ps) throws IOException {
    ps.write(EOL);
    ps.write(EOL);
    ps.println("The requested file could not be found.\n");
    void sendResponseFile(File targ, PrintStream ps) throws IOException {
    InputStream is = null;
    ps.write(EOL);
    if (targ.isDirectory()) { ;
    listDirectory(targ, ps);
    return;
    } else {
    is = new FileInputStream(targ.getAbsolutePath());
    try {
    int n;
    while ((n = is.read(buffer)) > 0) {
    ps.write(buffer, 0, n);
    } finally {
    is.close();
    /* mapping file extensions to content-types */
    static java.util.Hashtable map = new java.util.Hashtable();
    void listDirectory(File dir, PrintStream ps) throws IOException {
    ps.println("<TITLE>Multithreaded Webserver</TITLE><P>");
    ps.println("<html><body align=center>");
    ps.println("<center><h3><font color=#9999CC>Simple File Based MultiThreaded WebServer</font></h3></center>");
    ps.println("<table border=1 align=center>");
    ps.println("<tr bgcolor=#9999CC><td width=100% height=100% align=center><h3>Directory Listing</h3></td>");
    ps.println("<td width=40% height=40% align=center><h3>Type</h3></td>");
    String[] list = dir.list();
    for (int i = 0; list != null && i < list.length; i++) {
    File f = new File(dir, list);
    if (f.isDirectory()) {
    ps.println("<tr><td>");
    ps.println("<font size=\""+"2"+"\"face=\""+"Verdana"+"\"> <A HREF=\""+list[i]+"/\">"+list[i]+"</A></font><a href=\""+list[i]+"/\"></a>\n<BR></td>");
    ps.println("<td align=center><a href=\""+list[i]+"/\"><img src=\""+"/images/folder.jpg"+"\"></img></a>");
    ps.println("</td");
    ps.println("</tr>");
    } else {
    ps.println("<tr><td>");
    ps.println("<font size=\""+"2"+"\" face=\""+"Verdana"+"\"></A> <A HREF=\""+list[i]+"\">"+list[i]+"</A></font><A HREF=\""+list[i]+"\"></A>\n<BR></td>");
    ps.println("<td align=center><a href=\""+list[i]+"/\"><img src=\""+"/images/file.gif"+"\"></img></a>");
    ps.println("</tr>");
    ps.println("</table>");
    ps.println("<P><HR><I><font color=blue>"+(new Date())+"</font></I>");
    ps.println("<I><font color=blue>Copyright to HCL Technology Ltd</font></I>");
    ps.println("<I><font color=blue>Author Vivek Kumar Sinha</font></I>");
    ps.println("</body></html>");
    The ThreadPool class contains a Vector of WorkerThread objects.
    These objects are the individual threads that make up the pool.
    The WorkerThread objects will start at the time of their construction.
    If there are more HTTP requests than there are WorkerThreads,
    the extra requests will backlog until WorkerThreads free up.
    class ThreadPool extends WebServer{
    void createThreadPool(){
    for (int i = 1; i <= workerThreads; ++i) {
    Worker w = new Worker();
    Thread t=new Thread(w, "Worker Thread No."+i);
    t.start();
    /* Uncomment to check the number of worker threads running */
    // printString("Worker Thread No."+i+" Started");
    threads.addElement(w);
    try{
    ServerSocket serversocket = new ServerSocket(port);
    do {
    Socket socket = serversocket.accept();
    Worker w = null;
    synchronized (threads) {
    if (threads.isEmpty()) {
    /* Do nothing */
    } else {
    w = (Worker) threads.elementAt(0);
    threads.removeElementAt(0);
    w.setSocket(socket);
    } while (true);
    } catch (IOException e) {
    e.printStackTrace();

    Thank you for Welcoming me!!! I am very new to this forum so din't have this idea.
    I am unable to add the keep alive behavior . I don't have problem with any part of the code. The problem is i don't know how to make that enhancement in the existing code.
    Regards

  • Assign unique id to client of socket server

    HI
    I am in the process of developing a xml socket server application and have hit on a problem. I have managed to create a server that listens for connections and once a request is recieved creates a new client on a seperate thread with the reference being stored in a vector in the server.
    However I want to be able to assign an id to a client when it is created so that I can broadcast messages to specific users.

    my apologies my question was poorly stated..
    When i meant unique i mean that they will have already been prdefined i.e for example the following users
    Name David
    UserId *(Unique) 0138868
    Name sarah
    UserId *(Unique) 4138868
    Name rob
    UserId *(Unique) 7138868
    what i want to be able to is when the users connect they can be refeneced by their Userid so that if rob wants to say something to sarah without david knowing. The problem I have is that I do not know how to provide the userid to the server such that the server can create a new client thread with a specified id.
    Hope that makes sense ;>

  • Right way to communicate with a socket server (TCP/IP)

    Hi,
    I used to write data from my J2ME socket client to a J2EE socket server with writeUTF(). In this way I can send (and receive) directly Strings.
    When I need an XML file I ask the server with something like os.writeUTF(GIVE_ME_XML_FILE) and I use an XML parser with this socket InputStream.
    I was wondering if it's the right way to proceed ....?
    How do you guys communicate with a server when you need "to talk" a lot ? Do you use only HTTP requests or (if you are allowed to) do you use Socket with writeUTF ?
    Just to know if I'm completely wrong....and if I gonna have unsolicited issues ...
    Thanks..

    AdrienD wrote:
    When I need an XML file I ask the server with something like os.writeUTF(GIVE_ME_XML_FILE) and I use an XML parser with this socket InputStream.
    I was wondering if it's the right way to proceed ....?No, it is not. Read the writeUTF api docs, and you'll know why!
    How do you guys communicate with a server when you need "to talk" a lot ? Do you use only HTTP requests or (if you are allowed to) do you use Socket with writeUTF ?There is answer to this question. it al depends on what data gets send where, how often, and how large..

  • CLI0615E  Error receiving from socket, server is not responding.

    We recently changed a web application using DB2 5.2 tables from ODBC to JDBC. We are using the COM.ibm.db2.jdbc.net.driver. We are using a
    connection pool and running on iPlanet.
    We are getting intermittant "CLI0615E Error receiving from socket, server is not responding errors". We have looked in the JDBC forum and DB2 support and cannot find a reasonable answer to this problem. It is NOT always on sql statements that take a long time to execute, so I don't think it is a timeout issue.
    I read something about "stale connections". Does anyone know how to check to see if this is a problem?
    When we first converted the app, we had a lot of problems also with "invalid handle or statement is closed" which we have determined was being caused by the user submitting the page again before it had time to finish the first time. We have put in javascript code to prevent multiple submits. Could this server not responding problem be caused by double submits that we have not located yet?
    The error is NOT occuring on any one page, and the same page will run correctly once and the next time throw this error.
    Any suggestions would be greatly appreciated.
    Thanks.
    [29/Apr/2003:11:00:20] info (42196): COM.ibm.db2.jdbc.net.DB2Exception: [IBM][JDBC Driver] CLI0615E Error receiving from socket, server is not responding. SQLSTATE=08S01
         at COM.ibm.db2.jdbc.net.SQLExceptionGenerator.throwReceiveError(SQLExceptionGenerator.java(Compiled Code))
         at COM.ibm.db2.jdbc.net.DB2Request.receive(DB2Request.java(Compiled Code))
         at COM.ibm.db2.jdbc.net.DB2Request.sendAndRecv(DB2Request.java(Compiled Code))
         at COM.ibm.db2.jdbc.net.DB2RowObject.next(DB2RowObject.java(Compiled Code))
         at COM.ibm.db2.jdbc.net.DB2ResultSet.next(DB2ResultSet.java(Compiled Code))
         at bom.Bom.getDefs(Bom.java(Compiled Code))
         at jsps.bbapps._eng._ENGJGLT0_jsp._jspService(_ENGJGLT0_jsp.java(Compiled Code))
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:119)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.iplanet.server.http.servlet.NSServletRunner.invokeServletService(NSServletRunner.java:897)
         at com.iplanet.server.http.servlet.NSServletRunner.Service(NSServletRunner.java:464)

    hi,
    lemme try to tell u what i thinkk..i dont think its' a solution
    Usually this error code means that there was some problem while the driver tried establishsing a socket connection to the remote server. You could very well avoid this by tracking out what is preventing the socket connection.. it may be network congestion or some other onfiguration problems with the network, or with the DB2 server...
    But if the same application could work perfectly with jdbc-odbc driver in same environment,then it needs some attention.either the ibm driver isn't throwing the error as expected by the iplanet or iplanet isn't acting as needed when such an error is thrown.
    contact them and they may provide and explanation..
    wishes,
    Jer

  • Stream based socket , server implementation

    Please help me with this simple server and socket problem.
    SERVER_
    package com.supratim;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class SocketServer {
         private static ServerSocket server;
         public static void main(String[] args) throws IOException {
              server = new ServerSocket(9999);
              new SocketServer().go();
         private void go() throws IOException {
         while(true) {
              Socket socket = server.accept();
              DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
              DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
              byte[] buff=new byte[dataInputStream.available()];
              int i;
              while((i=dataInputStream.read())>0) {
                   dataInputStream.read(buff, 0, buff.length);
              String inputMessage="INPUT MESSAGE OBTAINED : "+new String(buff);
              byte[]outputBuffer = inputMessage.getBytes();
              dataOutputStream.write(outputBuffer);
              dataOutputStream.flush();     
              socket.close();
    CLIENT+
    package com.supratim;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class SocketClient {
         public static void main(String[] args) throws UnknownHostException, IOException {
              new SocketClient().go();
         private void go() throws UnknownHostException, IOException {
              Socket socket = new Socket("localhost",9999);
              InputStream dataInputStream = socket.getInputStream();
              OutputStream dataOutputStream = socket.getOutputStream();
              String inputMessage="ABCDEFGHIJKLMNOPQRSTWXYZ";
              byte[]outputBuffer = inputMessage.getBytes();
              dataOutputStream.write(outputBuffer);
              dataOutputStream.flush();     
              byte[] buff=new byte[dataInputStream.available()];
              int i;
              while((i=dataInputStream.read())>0) {
                   dataInputStream.read(buff, 0, buff.length);
              System.out.println("RESPONSE : "+new String(buff));
              socket.close();
    }When I try to connect to the SERVER from CLIENT, nothing happens. As soon as I terminate the CLIENT, the following stack trace comes...
           Exception in thread "main" java.net.SocketException: Connection reset
            at java.net.SocketInputStream.read(SocketInputStream.java:168)
            at java.net.SocketInputStream.read(SocketInputStream.java:182)
            at java.io.FilterInputStream.read(FilterInputStream.java:66)
            at com.supratim.SocketServer.go(SocketServer.java:26)
            at com.supratim.SocketServer.main(SocketServer.java:14)Please tell me, am I missing something??
    I dont want to use PrintWriter,BufferedReader,BufferedWriter...

    jverd wrote:
    supratim wrote:
    jverd wrote:
    supratim wrote:
    tjacobs01 wrote:
              while((i=dataInputStream.read())>0) {
                   dataInputStream.read(buff, 0, buff.length);
              }This is your problem. InputStream.read is going to block progressif it is so...how am I suppose to check the end of the stream....what is the way out??I'm not really sure what problem you're having or what you're asking. However, if your problem is that you want your server to be able to accept new connections while it's servicing an earlier conneciton--that is, service multiple requests at once--then, clearly, you need to use multiple threads. At the very least, one for accepting connections and one for servicing the requests that come on those connections.The problem is when the client is connecting to send a message as a byte stream...the message does not reach there..eventually the connection resets... why is that?? which part of the SocketServer is being blocked...and what is its way out??
    Let's say it is used in a single threaded environment..only one client is connecting at a time...Does the client flush()? Does it close() the Socket's OutputStream?
    If you don't flush(), data that you have sent may not be received.
    If you don't close(), the server won't know the client is done sending, so he'll never get the -1.
    (Or, alternative to calling OutputStream.close(), you could call Socket.shutdownOutput(), I think.)
    Edited by: jverd on Jul 12, 2011 10:49 AMplease check the code...flushing...closing are all there...

  • Can't connect java socket server in MAC OS

    Does any know what settings need to be done in order to connect socket server written in java on MACOS.
    my socket server is running on 5000 port, i've tried on running server on linux, and my program is able to receive the request from remote unix server.
    but when the server is running on mac OS, the the unix server couldn' connect to the socket.
    is this a port blocking problem?
    can someone tell me what to do to make server on MAC OS available for receiving request?
    Thanks

    Who is the sys/net admin for the Mac?

  • Keep a Socket Server connection/port open for incoming requests

    Hi,
    I have a socket server which listens to the incoming messages. The problem is that the socket server terminates the socket connection once it receives a message.
    I want this Socket server to keep on running and process all the requests it receives.
    Can you please advise which stream shall be kept open for this to be achieved? Below is the code for your reference.
    Thanks!
    import java.net.*;
    import java.io.*;
    public class SocketServer
         public static void main(String[] args) throws IOException
                 ServerSocket serverSocket = null;
                 String result = null;
                 SocketServer sockServer = new SocketServer();
                 try
                          serverSocket = new ServerSocket(4444);
                 catch (IOException e)
                          System.exit(1);
                 Socket clientSocket = null;
                 try
                      clientSocket = serverSocket.accept();
                          clientSocket.setSoTimeout(30000);
                 catch (IOException e)
                      System.exit(1);
                 PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                 BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                 String inputLine;
                 inputLine = in.readLine();
                 if((inputLine == null) || (inputLine.length() < 1))
                          throw new IOException("could not read from request stream");
                 else
                          result = sockServer.parseString(inputLine);
                          out.println("|0|OK|");
              InputStream is = null;
                  FileOutputStream fout=null;
                  BufferedInputStream bufIn = null;
                  HttpURLConnection con = null;
                  ByteArrayOutputStream baos = null;
                    try
                   URL url = new URL("http","10.176.96.64",8080,result);
                   con = (HttpURLConnection)url.openConnection();
                   is = con.getInputStream();
                   bufIn = new BufferedInputStream(is);
                   fout=new FileOutputStream("Z:\\Clips\\Cache\\"+result);
                   baos = new ByteArrayOutputStream();
                   int c = bufIn.read();
                   while(c != -1)
                        baos.write(c);
                        c = bufIn.read();
                   baos.writeTo(fout);
              catch(MalformedURLException mue)
                   System.err.println ("*********In Download File: Invalid URL");
              catch (IOException ioe)
                   System.err.println ("*********In Download File: I/O Error - " + ioe);
              finally
                   try
                        baos.close();
                        bufIn.close();
                        fout.close();
                        is.close();
                        con.disconnect();
                   catch(Exception ex)
                        System.out.println("*********In Download File: Exception Occured: "+ex.toString());
                      out.close();
                      in.close();
                      clientSocket.close();
                      serverSocket.close();
    }

    In a truly unexpected turn of events.. this question has been crossposted.
    http://forum.java.sun.com/thread.jspa?threadID=5127579
    Good job singalg. I highly recommend that instead of accepting that there is anything wrong with your understanding of how this should work and reviewing the tutorials you should instead repost this question daily, Each day choosing a different forum.

  • Problem with data socket server

    We have developed a program (from LabVIEW 6.1 running on Windows NT) consisting of a main executable and four other executables dedicated to collecting various i/o information. The four i/o executables convert raw data into process data and pass it on to the main executable using Data Sockets. The data is assembled as a cluster, then flattened into a string, which is published to a data socket variable. The data cluster contains a time stamp used by the main executable to verify i/o is being updated periodically (at least once a second). The main executable generates an alarm if the timestamp gets to be more than 5 to 15 seconds old, depending on the expected data. Typically, this alarm never happens, unless an i/o device is powered down o
    r disconnected, or an executable or Data Socket Server is terminated.
    The problem we are is experiencing is that false alarms are being generated, at precise intervals of exactly 5 days, 18 hours, 1 minute, and 1 second. The alarm condition occurs then clears immediately. The only thing I can think of is the data socket is somehow "cleared" for some reason at this interval, causing the main executable to momentarily read a time stamp of zero, and generate an alarm. Is there anything that might be corrupting the data sockets at a long interval like this? The worst thing is that the alarm horn gets falsely triggered, so we are trying to resolve this but can not see anything in any of the code to cause such an occurrence.
    Thanks in advance for your help.
    Brian Hajder
    Despatch Industries
    8860 207th Street West
    Lakeville, MN 55044
    Phone: 952.469.8111
    Fax: 952.469.4513
    [email protected]

    Hello Matt,
    Thank you for reading & responding. I should try to summarize this specific application in a little more detail.
    We have built a manufacturing tool for a customer that is controlled by a single Windows NT PC, for which we have developed 5 executables using LabView 6.1. The main executable provides the user interface. The other four executables are dedicated to control & monitoring of specific i/o devices (serial or IEEE-488). The i/o executables pass data to and receive commands from the main using data sockets. The PC is not on any type of network. The main executable supports an optional SEMI standard host link through its ethernet port, but that is not currently active or connected. A total of 13 data sockets are used, to implement si
    mple "one way" traffic through any socket, making buffering unnecessary. Some data sockets (i/o data to and from main) are updated a few times a second at most, commands from the main may only be updated a few times a day.
    Data from each of the i/o executables includes a time stamp indicating the last valid i/o hardware read time. The main uses this data from each i/o executable to determine whether i/o hardware is responding properly - if the timestamp gets to be anywhere from 5 to 15 seconds old (depending on which i/o is being checked), an i/o failure alarm for that device is raised.
    What seems to be happening is that, periodically, precisely every 496,861 seconds, two or more of the timestamps are found to be too old; I am assuming some external event is momentarily clearing socket data & the zero value timestamps look very old, thus triggering alarms at the exact same second. The alarm conditions clear up in less than one second.
    I wonder what you mean by "the datasocket
    server resetting"? Is this documented anywhere?
    Thanks for plowing through this wordy description, I appreciate any help you can suggest.
    Brian

  • Basic Socket Server Principles

    Hi - new to java, programming a socket server (working-ish) but not sure if the principles I am applying are appropriate.
    Basically, during the course of development I decoupled the socket server application logic from the socket server itself so that I could develop them independently. To that ends I have two abstract classes; Server and Service (posted below).from which I derive concrete subclasses (SampleServer and SampleService). The basic idea is that the server handles connections and initializes a service instance. The service obtains the client socket connection, and proceeds to read/write as needed. When the service stops (for whatever reason, error or by accomplishing a goal), the server is supposed to close connections, and wait again for another client.
    Thing is, I have no idea how efficient it is, or what best practice is. Of most concern is Server.run method (questions commented). Of almost equal concern is SampleService.doService(); In my experience, the client (I've been using a flash movie) seems to rarely recieve the entire stream of numbers.before the socket closes. I'd appreciate comments / criticisms / warnings / alternatives etc..
    Thanks in advance.
    David
    *Server.java
    package davi.fol
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.io.IOException;
    * @author David Foley
    public abstract class Server implements Runnable
        protected Thread _thread = null;
        protected Socket _socket = null;
        protected ServerSocket _server;
        protected Service _service;
        public Server(Service service) throws IOException
            _service = service;
            _server = new ServerSocket(_service.getPort());
         * start the server
        public void start()
            if (_thread == null)
                _thread = new Thread(this, _service.getName());
            _thread.start();
            log("- Server.start()");
         * Stop the server
         * @param status - -1 error state, 0 ok
        public void stop(int status)
            try
                stopService();
            catch (Exception exception)
                // uncomment below to fail silently.
                // exception.printStackTrace();
            finally
                _thread = null;
                log("- SocketServer.stop()");
                System.exit(status);
         * Entry point for determining if a an exception can be recovered from @see Server.recoverable
         * to operate if
         * @param exception
        public void recoverOrDie(Exception exception)
            log("- Server.recoverOrDie()");
            if (!recoverable(exception))
                exception.printStackTrace();
                stop(-1);
         * Override this method to obtain an opportunity
         * to handle an exception if encountered. Default @return false
         * @param exception
         * @return
        public Boolean recoverable(Exception exception)
            return false;
        public void run()
            try
                while (_thread.isAlive()) // is this correct?
                    startService(); //initialize the service, passing _socket to Service.start method
                    while (_service.isRunning())
                         // don't do anything else while _service.isRunning == true
                    stopService();
            catch (Exception e)
                recoverOrDie(e);
         * waits until a client connects
         * @throws java.io.IOException
        private void startService() throws IOException
            _socket = _server.accept();
             _service.start(this, _socket);
            log("- Server.openSocket()");
        private void stopService() throws IOException
            if (_socket != null)
                _socket.close();
                _socket = null;
            log("- Server.closeSocket()");
             _service.stop();
        public void log(String message)
            System.out.println(message);
    }And this is the Service class...
    * Service.java
    * Created on 03-Nov-2007 at 18:15:22
    package davi.fol;
    import java.net.Socket;
    import java.io.IOException;
    * @author David Foley
    abstract public class Service
        protected Server _server;
        protected Socket _client = null;
        protected int _port;
        protected String _name;
        protected Boolean _running = true;
         * Service decouples server logic from service logic by centralizing
         * basic server methods with an instance of server
         * @param port
         * @param name
        public Service(int port, String name)
            _port = port;
            _name = name;
         * @return the port number on which the service is opertaing
        public int getPort()
            return _port;
         * @return the name of the service
        public String getName()
            return _name;
         * default method. Override
        public void stop ()
            _running = false;
         * Called by the server when a client connects, providing the
         * service an opportunity to generate and manage its own
         * client io
         * @param server
         * @param client
         * @throws java.io.IOException
        public void start (Server server, Socket client) throws IOException
            _client = client;
            _server = server;
         * @return whetjer the service is running
       abstract public Boolean isRunning();
         * @param message
        public void log(String message)
            //System.out.println(message);
            if(_server != null)
                _server.log(message);
         * @throws java.io.IOException
        abstract public void doService() throws IOException;
    }An sample service (just writes ints to client socket)
    * SampleService.java
    * Created on 05-Nov-2007 at 14:52:11
    package davi.fol;
    import java.io.OutputStream;
    import java.io.IOException;
    * @author onDevice
    public class SampleService extends Service
        public SampleService(int port)
            super(port, "SampleService");
         * @see Service.start(Server server, Socket client)
         * writes the integers 100 to 0 inclusive to the client socket
        public void doService() throws IOException
            OutputStream out = _client.getOutputStream();
            int count = 100;
            while (count > -1)
                out.write(count);
                count--;
            out.close();
            stop();
    * SampleServer.java
    * Created on 05-Nov-2007 at 14:50:55
    package davi.fol;
    import java.io.IOException;
    // just initializes an instance of SampleServer
    public class SampleServer extends Server
        public SampleServer () throws IOException
            super(new SampleService(3000));
    }Edited by: ondevice on Nov 5, 2007 7:31 AM

    Yeah, I've also used jpcap too...same problem because it wraps around WinPCap dll just like Wireshark/Ethereal. No lucks. I even tried Windump, same deal. It seems like so many of these sniffers are built as a wrapper around WinPCap dll so that might be the limiting factor.
    However, I know this this is doable because I have had lucks using:
    http://www.sstinc.com/winsock.html
    But this product is only limited toward Windows OS. I would like to implement this into java so I can operate my application under windows, linux, unix, and mac.
    Would you have any ideas how
    SSTINC built their Winsock analyzer? I'm sure there has got to be a way to work around this....
    Does anyone know if there is a Unix/Linux socket shim/analyzer out there? I'll have my boss buy it if java can not answer our problem.

  • Changing socket server config at runtime

    Is it possible to modify properties of a socket server at runtime without needing to change the xml? For example, if I wanted to change something like connection-idle-timeout-minutes from 120 to 60, could I do it without modifying the following xml block in services-config.xml and redeploying?
         <server id="my-nio-server" class="flex.messaging.socketserver.SocketServer">
                <properties>
                    <connection-idle-timeout-minutes>120</connection-idle-timeout-minutes>
                    <socket-keep-alive-enabled>true</socket-keep-alive-enabled>
                    <max-worker-threads>200</max-worker-threads>
                    <min-worker-threads>200</min-worker-threads>
                    <accept-thread-priority>7</accept-thread-priority>
                    <accept-backlog>25</accept-backlog>               
                </properties>
            </server>
    I ask because our application is large enough that off cycle deploys or downtimes are rarely feasible, and it would be convenient if there were a way to change these values at runtime.

    It looks like it might be possible although none of the APIs you need to do it are published.
    I can tell you what the APIs are if you want to give it a try and see if it works for you.
    The flex.messaging.socketserver.SocketServer class has a setConnectionIdleTimeoutSeconds(int value) method that you can call to change the connection idle timeout. It looks like this is thread safe so you should just need to get the SocketServer at runtime and call the method.
    NIO endpoints that extend from flex.messaging.endpoints.BaseSocketServerEndpoint have a getSocketServer() method you can use to get the SocketServer.
    You can get an NIO endpoint from the MessageBroker by calling getEndpoint(String) and passing in the endpoint id or getEndpoints() to get a Map of all the endpoints.
    So, to sum up, you should be able to first get the MessageBroker. For example, in a servlet you can call FlexContext.getmessageBroker() to get it. Next, you would get the endpoint from the MessageBroker and then get the SocketServer from the endpoint. Once you have the SocketServer, you should be able to call setConnectionIdleTimeoutSeconds to change the connection idle timeout.
    Hope that helps.
    -Alex

  • Error 42 occurred when writing to data socket server?

    Hi
    Attached are two programs which use data socket to transfer a boolean value. I want to make sure the value only transfer one time. It occurred error 42 at the test server.vi when it write to the data socket server. How can I solve that? Are there any methods to ensure the data can be transferred one time? Thanks.
    Bill
    Attachments:
    Test_client.vi ‏29 KB
    Test_server.vi ‏47 KB

    I am using LabVIEW 7 and I did not see the error on my machine when I ran your programs.
    From the way you want to transmitt data, I think you need to use TCP/IP instead of datasocket. This way you can be sure that the data only got read once. There are several shipping examples to get you started.
    If you have LabVIEW 7 you might consider using the buffered datasocket. I am not sure if it will work in the way you want so experiment.

  • Firewall: Error sending to the socket, server is not responding.

    Hi all,
    I'm trying to connect AIX machine to NT DB2 Database through JDBC with a firewall. I'm using the standard port 6789 in JDBC Applet Server in NT DB2. But I've gotten the following message:
    COM.ibm.db2.jdbc.DB2Exception: [IBM][JDBC Driver] CLI0614E Error sending to the socket, server is not responding. SQLSTATE=08S01
    The connection chain I'm using for AIX side is:
    jdbc:db2://192.168.3.4:6789/DATABASE
    I've configured the firewal to allow the port 6789 to be used, and also the other port 51544 (it's for remote administration, I think). I've also checked that wires and other stuff is working fine, but stil I cannot connect to the Database.
    I don't know if there's something missing on the firewall configuration. Before, everything was working without the firewall.
    Any help will be apreciated, THanks.
    Rodrigo, SPAIN

    It looks like no port problem is happening, because we freed all the ports just to see if client tried to use some of them without our knowing. But it was still the same.
    We were thinking about routing issues, but we were able to ping from client to server, and ports 6789 and 51544 were open as well. Maybe JDBC Client Driver is looking for an different IP address than 192.168.3.4. We know the firewall doesn't receive any query from JDBC Client, and that's very strange because if you see the routing tables in AIX machine, the default route is the firewall. Of course, there's not any other static defined route for the server (192.168.3.4), so it's supposed that default route is going to be used. But it's not.
    We also restarted client machine from scratch but nothing. Maybe this problem happens because there's something wrong in AIX networking settings.
    Rodrigo

Maybe you are looking for

  • Im new to mac's. and everytime i try to video chat. an error occurs.

    Date/Time: 2008-12-05 22:58:05.756 -0500 OS Version: 10.5.5 (Build 9F33) Report Version: 4 iChat Connection Log: 2008-12-05 22:57:38 -0500: AVChat started with ID 3143574352. 2008-12-05 22:57:38 -0500: thekidtjacks: State change from AVChatNoState to

  • SAPScript / Smartform printing with all #

    Hi, I am facing a strange problem while printing Script and Smart forms. We are using QM02 transaction to print the deviation form and MRDR form. Deviation form is a script and MRDR is a smartform. The problem is, when i executed the QM02 and print a

  • Dell Laptop Solaris Installation

    Hi I have Dell Inspiron 8100 with P-III, 256 MB RAM. I would like to install Solaris(Intel) 8 10/01on this. When I run installation, after device check it gives an error: epb0: M II link not found. and when it asking to enter laguage option, it won't

  • CD ROM drive problem after upgrade to 10

    Had Solaris 8, worked fine for years. Upgrade to 10 an now the CD rom drive does not work properly. When you put in ANY CD, it goes in, spins for about 30 seconds, then the door opens and stays open. No file manager windows open, I cannot access the

  • Firefox 3.6.15 won't download (Windows 7)

    Firefox 3.6.15 won't download in Windows7. The download window just runs, don't even connect with the server