Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Help. Multi Threading with sockets in client/server environment

  1. #1
    Junior Member
    Join Date
    Feb 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Help. Multi Threading with sockets in client/server environment

    I'm having trouble introduce multi‐threading in SimpleServer.java. I need to make it so ther server can handle an arbitrary number of client connections simultaneously. That so, each time the server receives a new incoming client connection, spawn a new thread that will process that particular connection.

    So I could implement a loop such as:

    while(true){
    try{
    //server.accept returns a client connection
    Thread t = new Thread(w);
    t.start();
    } catch (IOException e) {
    System.exit(-1);
    }

    And implement it in the SimpleServer class around where I create a new Socket

    Socket skt = myServerSocket.accept();

    And than I'm not sure which code I have to move to the:
    Publie void Run() method.

    Here are the Sever and Client Classes. Sorry when I pasted it killed the formating..

    Server Class

    import java.io.;
    import java.net.;
     
    /
    Simple server using Java Sockets.
     
    /
    public class SimpleServer {
     
    /*
    @param args
    /
    public static void main(String[] args) {
     
    try {
    // First we create a server socket and bind it to port 9999.
    ServerSocket myServerSocket = new ServerSocket(9999);
     
    // server processes incoming client connections forever...
    while (true) {
     
    // wait for an incoming connection...
    System.out.println("Server is waiting for an incoming connection on host="
    InetAddress.getLocalHost().getCanonicalHostName()
    " port=" myServerSocket.getLocalPort());
     
    Socket skt = myServerSocket.accept();
     
    // ok, got a connection. Let's use java.io. niceties to read and write from the connection.
    BufferedReader inputFromClient = new BufferedReader(new InputStreamReader(skt.getInputStream()));
    PrintStream outputToClient = new PrintStream(skt.getOutputStream());
     
    boolean connectionClosed = false;
    while(!connectionClosed) {
    // attempt to read input from the stream.
    String buf = inputFromClient.readLine();
     
    // if we got input, print it out and write a message back to the remote client..
    if (buf != null) {
    System.out.println("Server read: [" buf "]");
    outputToClient.println(buf);
    } else {
    connectionClosed = true;
    }
    }
     
    // close the connection.
    skt.close();
    System.out.println("Connection to client closed. Server is now going to wait for another connection.");
    }
    } catch (IOException ex) {
    ex.printStackTrace();
    System.out.println("Whoops, something bad happened! I'm outta here.");
    }





    Client Class

    import java.io.;
    import java.net.;
     
    /*
    Simple client using Java Sockets.
     
    /
    public class SimpleClient {
     
    /*
    @param args
    /
    public static void main(String[] args) {
     
    // create a socket and find it to the host/port server is listening on.
    String host;
    int port;
     
    if(args.length==0) {
    host = "localhost";
    port = 9999;
    } else {
    host = args[0];
    String portStr = args[1];
    try {
    port = Integer.parseInt(portStr);
    } catch (NumberFormatException nfe) {
    System.out.println("Whoops, invalid port number. Will default to 9999");
    port = 9999;
    }
    }
     
    try {
    System.out.println("Client will attempt connecting to server at host=" host " port=" port ".");
    Socket skt = new Socket(host,port);
     
    // ok, got a connection. Let's use java.io.* niceties to read and write from the connection.
    BufferedReader myInput = new BufferedReader(new InputStreamReader(skt.getInputStream()));
    BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
     
    PrintStream myOutput = new PrintStream(skt.getOutputStream());
     
    boolean done = false;
     
    while (!done) {
     
    // prompt and read from console
    System.out.print("Enter a message, or enter \"done\" to quit: ");
    String buf = consoleInput.readLine();
     
    if(buf != null) {
    if(buf.equalsIgnoreCase("done")) {
    done = true;
    } else {
     
    // write something to the server.
    myOutput.println(buf);
     
    // see if the server echoes it back.
    buf = myInput.readLine();
    if(buf != null) {
    System.out.println("Client received [" buf + "] from the server!");
    }
     
    }
    } else {
    done = true;
    }
    }
     
    // we're done, let's get out of dodge!
    skt.close();
    System.out.println("Client is exiting.");
     
     
    } catch (IOException ex) {
    ex.printStackTrace();
    System.out.println("Whoops, something bad happened! I'm outta here.");
    }
     
     
    }
     
    }
     
     
    }
     
    }
    Last edited by Json; March 23rd, 2010 at 03:20 AM. Reason: Please use code tags!


  2. #2
    Junior Member
    Join Date
    Mar 2010
    Location
    Home-Ujjain /Job-Mumbai
    Posts
    24
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help. Multi Threading with sockets in client/server environment

    Study this code and use it as the base for your server This code is working properly
    Contact me if you have any query at sunil1raghu@gmail.com

    import java.net.*;
    import java.io.*;
    /**
     *
     * @author Sunil Raghuvanshi
     */
    public class MyServer
    {
        private ServerSocket sk;
        private Socket ck;
        MyServer()
        {
            try
            {
                sk= new ServerSocket(3033);
                startListening();
            }catch(Exception e)
            {
                System.out.println(e);
            }
        }
        public void startListening()
        {
            try
            {
                while(true)
                {
                  System.out.println("Server is listening");
                  ck=sk.accept();
                  System.out.println("A Client has been connected and diverted to" + ck.getPort());
                  RequestProcessor rp;
                  rp=new RequestProcessor(ck);
               }
            }catch(Exception e)
            {
                System.out.println(e);
            }
        }
        public static void main(String args[])
        {
            MyServer cs=new MyServer();
        }
    }
    class RequestProcessor extends Thread
    {
        private Socket cc;
        RequestProcessor(Socket j)
        {
            cc=j;
            start();
        }
        public void run()
        {
            try
           {
                InputStream i;
                InputStreamReader ir;
                OutputStream o;
                OutputStreamWriter ow;
                StringBuffer sb;
                String s;
                System.out.println("Reading request stream");
                i=cc.getInputStream();
                ir=new InputStreamReader(i);
                sb=new StringBuffer();
                int x;
                while(true)
                {
                    x=ir.read();
                    if(x==-1 || x=='\n')
                    {
                        break;
                    }
                    sb.append((char)x);
                }
                s=sb.toString();
                System.out.println("Request Stream"+s);
                int x1,x2;
                x1=s.indexOf(',');
                x2=s.indexOf(',',x1+1);
     
                String pc1,pc2,pc3;
                pc1=s.substring(0,x1);
                pc2=s.substring(x1+1,x2);
                pc3=s.substring(x2+1);
                System.out.println("Storing the data...");
                System.out.println("Roll Number"+pc1);
                System.out.println("Name"+pc2);
                System.out.println("Sex :"+pc3);
                RandomAccessFile raf=new RandomAccessFile(new File("C:\\student.txt"),"rw");
                raf.seek(raf.length());
                raf.writeBytes(pc1+"\n"+pc2+"\n"+pc3);
                raf.close();
                System.out.println("Sending Response");
                s="Record Saved\n";
                o=cc.getOutputStream();
                ow=new OutputStreamWriter(o);
                ow.write(s);
                ow.flush();
                ir.close();
                ow.close();
                cc.close();
            }catch(Exception e)
            {
                System.out.println(e);
            }
        }
    }

    Good Luck
    Last edited by Json; March 23rd, 2010 at 03:18 AM. Reason: Please use code tags.

Similar Threads

  1. nebeans client server connectivity ??
    By zeeshanmirza in forum Java IDEs
    Replies: 0
    Last Post: February 22nd, 2010, 11:30 PM
  2. [SOLVED] The concept of Server and Client
    By rendy.dev in forum Java Theory & Questions
    Replies: 3
    Last Post: January 18th, 2010, 04:13 AM
  3. Problems with client/server application
    By lori in forum AWT / Java Swing
    Replies: 3
    Last Post: January 15th, 2010, 01:12 PM
  4. Simple server-client trouble
    By DC200 in forum Java Networking
    Replies: 3
    Last Post: November 12th, 2009, 08:16 AM
  5. Download a file to client from server
    By mvittalreddy in forum Java Networking
    Replies: 4
    Last Post: October 5th, 2009, 04:23 AM