Server socket programming and thread

hello,
briefly this is what i have sought out to do : the server waits for the client indefinitely,upon a client requesting for service by writing a service id into the socket, a new thread of the type id as read by the server which is a sub-class of the Server (main-class) is exec'd.
the problem as i understand is that the client can send as much of data as it desires to the server and the thread can read the data it receives by the clients.the server(thread) fails to write reply to the client;eventhough out.write() is successful;the client is blocked in read() indefinitely.is it because of the thread which runs at a different port the client does not know and the server is not redirecting response to the client.
how do i read what the server(thread) writes onto the socket from the clients.

thanks again,just check out this code please
public class Server extends Thread //create a multi-threaded server
    /* *Creates a new instance of Server  */
    String                           serverAddr=CodeServer.ServerRun.SERVER_IP_ADDR;
    int                              serverPortNum=CodeServer.ServerRun.SERVER_TCP_PORT;   
    ServerSocket                     sSock;
    Socket                           cSocket;
    int                              requestID=0;
    boolean                          debug=true;  
    InputStream                      in =null;
    OutputStream                     out=null;
    Server ()
    Server (Socket csocket)
        this.cSocket = csocket;
    /* start the server at specifed portNum */
    private void initialise ()
        try
            //start the server at serverPortNum
            sSock=new ServerSocket (serverPortNum);
        catch (IOException ex)
            ex.printStackTrace ();
        /* console output of status of server */
        if(debug==true)
            System.out.println ("Server waiting @ "+sSock);
    private void acceptRequest ()
        try
            this.cSocket=sSock.accept ();
            if(debug==true)
                System.out.println ("client socket @ "+cSocket);
        catch (IOException ex)
            ex.printStackTrace ();
    private void readRequestID ()
        /*step 1: determine the type of server before threading
         *a request the the type of server got by the request ID
         * number */       
        try
            in        =cSocket.getInputStream ();
            requestID =in.read ();
            out       =cSocket.getOutputStream ();
            if(debug==true)
                System.out.println ("accross the client:"+requestID);
        catch (IOException ex)
            ex.printStackTrace ();
    private void execThreadForRequest ()
        /*step 2: after requestID is received on the socket.
         *its time to decide the server to thread the control into.
        switch(requestID)
            case 1: //invoke the RegisterServer thread
                new CodeServer.Core.RegistrationServer (this.cSocket).start ();
                break;
            case 2: //invoke the ListingServer thread
                break;
            case 3: //invoke the MessageTransferServer thread
                break;
            case 4: //invoke the CallSetupServer thread
                break;
            case 5: //invoke the DisconnectServer thread
                break;
            case 6: //invoke the ChangeUserStatusServer thread
                break;
    public void run ()
        // client processing code here==super class does nothing here
    public static void main (String args[]) throws Exception
        Server s=new Server ();
        s.initialise ();
        /* start indefinitely the main server thread */
        while (true)
           /* accept() blocks the server for a request
              a new request is put into a thread for processing */
            s.acceptRequest (); //initialise the clientSocket
            s.readRequestID (); //get the actual requested service
            s.execThreadForRequest (); //start the actual server thread
/**registration service class;
*registers the IP address of the caller,callee and the status
*adds the caller to the hash table and updates status
class RegistrationServer extends Server
    Socket              cSocket;
    InetAddress         clientAddr;
    DataInputStream     inStream;
    DataOutputStream    outStream;
    //Socket s=new Socket()
    RegistrationServer (Socket cSocket)
        this.cSocket=cSocket;
        clientAddr =cSocket.getInetAddress ();
        try
            //init for reading status and custom message.
            inStream     =new DataInputStream (cSocket.getInputStream ());
            outStream    =new DataOutputStream (cSocket.getOutputStream ());
        catch (IOException ex)
            ex.printStackTrace ();
        if(CodeServer.ROO.DEBUG==true)
            System.out.println ("register server:"+cSocket
                               +" host ip:"+clientAddr.getHostName ());
    public void run ()
        int    status=0;
        String custMesg=null;
        try
            /* read the custom message */
            if(inStream.available ()>0)
                try
                    custMesg=inStream.readUTF ();
                    System.out.println (""+custMesg);
                catch(EOFException e)
                    e.printStackTrace ();
            else
                custMesg="";
        catch (IOException ex)
            ex.printStackTrace ();
            try
                       here is the problem, i found if i try reading accross the client             
                       i only receive a junk value 81 always */
                   outStream.write(1); //write success
                    outStream.flush();
            catch (IOException ex)
                ex.printStackTrace ();
}and with the client GUI :thanks for the help.please do find time to help me out with a suggestion or two on this code.

Similar Messages

  • Socket programming and thread

    Hi all,
    I am getting problem while reading or writing to a port.
    we have two different thread for reading and writing, are they synchronize by itself or we have to make it explictly.
    the error i get are either of these two:
    1) java.io.EOFException
    2) java.net.SocketException: Broken pipe

    i am writing server and client which is thread based, i have implemented the biderectional ,first client writes to server. server reads from client first and then writes to client ,after server write client is not able to read data written by server. i am using the ObjectRead and Object Write methods of socket .
    At client when i read it gives the following error java.io.StreamCorruptedException
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at com.canarys.web.pushlet.newClient.run(Client.java:93)
    please help me out how to avoid this, the object i am using is serialised, if any of u need more clarification i will paste the code also
    any help regarding this will be appreciated

  • Can i run UDP  client and UDP  server socket program in the same pc ?

    hi all.
    when i execute my UDP client socket program and UDP server socket program in the same pc ,
    It's will shown the error msg :
    "Address already in use: Cannot bind"
    but if i run UDP client socket program in the remote pc and UDP server socket program run in local pc , it's will success.
    anybody know what's going on ?
    any help will be appreciated !

    bobby92 wrote:
    i have use a specified port for UDP server side , and for client define the server port "DatagramSocket clientSocket= new DatagramSocket(Server_PORT);"Why? The port you provide here is not the target port. It's the local port you listen on. That's only necessary when you want other hosts to connect to you (i.e. when you're acting as a server).
    The server should be using that constructor, the client should not be specifying a port.
    so when i start the udp server code to listen in local pc , then when i start UDP client code in local pc ,i will get the error "Address already in use: Cannot bind"Because your client tries to bind to the same port that the server already bound to.

  • Help on Server Socket Programming??????

    hello Friends,
    I need your help on following:
    I am the only person working on this project and the company wants me to prepare a infrastructure of this project and I should also give a demo of this project to my seniors. I will breif you up with my project:
    1. There is this gif image of distillation column. i will be publishing it using JApplet or Applet.
    2. This Image must be seen on internet.
    3. On the circle of these Image the user will click(In all there are five circles, called as controllers)and a dialog box should open thru which user will input the float values(I am using the JOptionPane class to open this dialog box).
    4. The inputed values will the be given to the C program which is the simulator for distillation column.
    5. The C program will generate the output through iterations(Code entirely in C), the output of each program will then be poped up to over the image beside the respective controlled or under the respective controller but definetely over the same gif file.
    6. The number of iteration will depend on how fast the C program converges the inputer parameters. And each output must be show over the gif image and when the final iteration value will appear it should remain on the image until some new value is inputted by the user again by clicking on any of the circle.
    The proposed theory to do this project accoding to me is as follows:
    1. Since each value must be thrown to the user. I beleive this is a real time project. So I decided to use Client Server Networking technology provided by java.
    2. Then I figured out that in this project there should be 2 clients One is the GUI which is the Image screen to receive the input from the user and to show the output to the user. Second client is a java program sitting behind the server which will receive this input data from user and it will have an NATIVE method through which all this input will be given to the C simulator program.
    3. The middle bridge between these two clients will be a server. Which will just pass the data to and fro from both the clients.
    3. The C program will perform iterations using these input values from second client. This C program will then give each iterations output to the Java program using JNI technology. This second client then sends this output value to the GUI clients through server.
    Well another very important thing, I am inexperience in the field of software so I had to do a lot of R&D and this is what I found out. Frankly I am really not sure whether this is the right path to approach to this project or there is some other correct and realistic way than this? Well friends i would certainly request you if you can suggest some other simple or rather correct path or else if this is the right path then would you please suggest me the possible hiches or perticular points where I should concentrate more.
    Well i am eagerly waiting for your reply.

    Since you are publishing your results on the net , it will be a better idea to use JSP?Servlet/Beans architecture instead of swing
    I will propose a architecture as follows:
    Client : Standard Browsers, IE and NS
    Middle Tier: Java Webserver/Application Server
    This will depend on your budget. If u have a fat allowance go for weblogic/websphere . If u are operationg on shoe string budget try for apache , etc
    In the server tier code your application in the follwing architecture
    JSP for presentation: Distillation towers picture, input boxes .. etc
    Servlets for business logic invocation and routing requests: Your JSP submits input values to servlets, which does the processing using Java Bean Components. Since you have a lot of Logic written in C I would suggest to encapsulate these in JavaBean components using JNI technology and reuse the code.
    After processing the servlet again forwards the response to another JSP for output
    Advantages:
    1.Your clients can be thin as most of the processing is done at the server
    2. Thread Management is taken care of by your webserver, which otherwise would be a headache
    3. Writing this through low level socket programming will be much more difficult as you will write your own protocol for communication this will be error prone and not scalable
    If you still decide to go for traditional client server programming using swing, use RMI for communication as I insist that socket programming is very very cumbersome...using your own protocols
    hope this helps
    Shubhrajit

  • Server socket programming issue

    Hi there and thanks for visiting my post,
    I'm writing a instant message application. I've written a multi-threaded server that constant listens for socket connections on port 4001. When a connection is received by the server, it adds the thread (client) connection to an array (of fixed size, I allow a max of 100 connections or so) and starts the thread. Here's the code:
    import java.io.*;
    import java.util.*;
    import java.net.*;
    * @author Stephen
    public class Main {
        static ServerSocket         sock = null;
        static pmClientHandler      conn;
        static Socket               client = null;  
        static int                  port = 4001;
        static int                  MAX_CONNECTIONS = 100;
        static pmClientHandler      t[] = new pmClientHandler[MAX_CONNECTIONS]; // array that holds threads holds a max of 100 now
        /** Creates a new instance of Main */
        public Main() { }
         * Instantiate server listener
         * @param args the command line arguments
        public static void main(String[] args) {
            // TODO code application logic here
            try {
                sock = new ServerSocket(port);  // listen on port
            } catch (IOException e) {
                System.out.println("Cannot create server on port "+port+".");
                System.exit(1);
            System.out.println("Pita messenger server ready on port  "+port+". Listening for connections...\n\n");
            while (true) {    // infinite loop to listingen for many connections
                try {
                client = sock.accept();  // accept connection
                for (int i =0; i < MAX_CONNECTIONS; i++) {
                    if (t[i] == null) {
                       (t[i] = new pmClientHandler(client,t,MAX_CONNECTIONS)).start();
                       break;      
                } catch (IOException e) {  // ERROR ACCEPTING CONNECTION 
            } // end infini. loop listening for remote socket connections
    }Again, each instance thread object of pmClientHandler constantly listens for incoming messages from the client application. Here's the code for that class.
    import java.util.*;
    import java.net.*;
    import java.io.*;
    public class pmClientHandler extends Thread {
    public String       username = "";
    private boolean     userValidated = false;
    public boolean      userAway = false;
    public boolean      userInvisible = false;
    public boolean      userBusy = false;
    private ArrayList   currentBuddyList;
    public Socket      connection;
    public pmClientHandler t[];
    private Scanner     reciever;
    public PrintStream  sender = null;
    private int         MAX_CONNECTIONS;
    private boolean     isConnected = false;
        /** Creates a new instance of pmClientHandler */
        public pmClientHandler(Socket s, pmClientHandler[] newThread, int maxc) {
            connection = s; // hand over socket
            MAX_CONNECTIONS = maxc;
            t = newThread; // hand over thread. We now have new populate array of clients in t[]
            isConnected = true;  // user connected
            try {  // create IO streams for this particular client
                reciever = new Scanner(connection.getInputStream()); 
                sender = new PrintStream(connection.getOutputStream(), true);  //auto flush true
            } catch (IOException e) { close(); }
         * Required method by threads. Method is called when thread is executed.
         public void run() {
          String clientMessage;
          pmServerMessenger resource = new pmServerMessenger();
          while(isConnected) { 
            // Determine username and password request
            clientMessage = reciever.nextLine().trim();
            ///////////////////////  HANDLE PROTOCOL / MESSAGES  /////////////////////////////////
            // So we know user has established a connection to the server but has not yet logged in yet.
            if (clientMessage.toUpperCase().startsWith("ECHO")) { sender.println("ECHO BACK, HELLO CLIENT"); }
            if (clientMessage.startsWith("LOGIN")) {  // client wishes to log in
                clientMessage = clientMessage.substring(5).trim();
                if (clientMessage.indexOf(" ") != -1) {
                    String suppliedUsername, suppliedPassword;
                    suppliedUsername = clientMessage.substring(0, clientMessage.indexOf(" ")).trim();
                    suppliedPassword = clientMessage.substring(clientMessage.indexOf(" ")).trim();
                    // Valid user
                    if (resource.validateUser(suppliedUsername, suppliedPassword)) {    
                        sender.println("ACDFG324323DSSDGTRR54745345DFGDFSE3423423DHDFHER4565DFGDFGERT");  // send key to client
                        userValidated = true;   // set flag to allow user to access server resources.
                        this.username = suppliedUsername;
                    } else {
                        sender.println("INVALIDLOGIN");
                } else {
                    sender.println("INVALIDLOGIN");
                    this.close();
            } // end user login routine //////////////////////////////////////////////
            if (clientMessage.toUpperCase().startsWith("LOADBUDDYLIST")) {
                if (isConnected && userValidated) {
                    ArrayList thisUsersBuddyList = resource.getBuddyList(this.username);
                    for (int i = 0; i < thisUsersBuddyList.size(); i++) {
                        String currBuddy = (String) thisUsersBuddyList.get(i);
                        if (currBuddy != "" && currBuddy != null) {
                            sender.println(currBuddy);
                    sender.println("ENDBUDDYLIST");  // let client know we're done sending client buddy list
            if (clientMessage.toUpperCase().startsWith("ISONLINE")) {
                String usrToCheck = clientMessage.substring(8).trim();
                if (isOnline(usrToCheck)) {
                    sender.println("YES "+usrToCheck);
                } else {
                    sender.println("NO "+usrToCheck);
            if (clientMessage.toUpperCase().startsWith("ISAWAY")) {
                String usrToCheck = clientMessage.substring(6).trim();
                if (isUserAway(usrToCheck)) {
                    sender.println("Z "+usrToCheck);  // is away
                } else {
                    sender.println("X "+usrToCheck);  // not away
            if (clientMessage.toUpperCase().startsWith("CLIENTAWAY")) {
                String usrToCheck = clientMessage.substring(10).trim();
                if (!usrToCheck.trim().equals("")) {
                    setClientAsAway(usrToCheck);
            if (clientMessage.toUpperCase().startsWith("CLIENTBACK")) {
                String usrToCheck = clientMessage.substring(10).trim();
                if (!usrToCheck.trim().equals("")) {
                    setClientAsBack(usrToCheck);
            // Exit the clients connection to the server.
            if (clientMessage.toUpperCase().startsWith("EXIT")) {
                sender.println("GOODBYE");
                this.close();
            if (clientMessage.toUpperCase().startsWith("WHOISONLINE")) {
                whoisOnline();
            if (clientMessage.toUpperCase().startsWith("DISPATCHIM")) {
                String imStr = clientMessage.substring(1).trim();
                String to = imStr.substring(0,imStr.indexOf(" ")).trim();
                String imMsg = imStr.substring(imStr.indexOf(" ")).trim();
                dispatchIM(to,imMsg);  
          }  // end while is connected
        } // End run method
         public synchronized void addIMToQueue(String from, String msg) {
             instantMessage im = new instantMessage(from,msg);
             imQueue.addLast(im);
         private synchronized void getInstantMessages() {
             while (!imQueue.isEmpty()) {
                 instantMessage tmpMsg = imQueue.remove();
                 String tmpHandle = tmpMsg.getHandle();
                 String tmpImMsg = tmpMsg.getMsg();
                 sender.println("L "+tmpHandle+" "+tmpImMsg);
             sender.println("IMPOPDONE");
         private void dispatchIM(String to, String m) {
            for (int i = 0; i < MAX_CONNECTIONS; i++) {
                if (t[i] != null) {
                    if (t.username.trim().equals(to)) {
    pmClientHandler x = t[i];
    PrintStream ps = x.sender;
    ps.println("IMMSG "+this.username+" "+m);
    * Method will relay back to client a list of who's online. When it's finished
    * the command DONELISTING is dispatched.
    private void whoisOnline() {
    for(int i=0; i < MAX_CONNECTIONS; i++) {
    if (t[i] != null && t[i].username.trim() != "")
    sender.println(t[i].username);
    sender.println("DONELISTING"); // so client knows we're done
    } // END whoisOnline METHOD
    private boolean isOnline(String user) {
    boolean isOn = false;
    for (int i = 0; i < MAX_CONNECTIONS; i++) {
    if (t[i] != null && t[i].username.trim().equals(user.trim())) {
    isOn = true; break;
    return isOn;
    private boolean isUserAway(String user) {
    boolean tmpIsAway = false;
    for (int i = 0; i < MAX_CONNECTIONS; i++) {
    if (t[i] != null) {
    if (t[i].username.trim().equals(user)) {
    if (t[i].userAway) {
    tmpIsAway = true;
    break;
    } else {
    break;
    return tmpIsAway;
    private void setClientAsAway(String user) {
    //this.userAway = true;
    for (int i = 0; i < MAX_CONNECTIONS; i++) {
    if (t[i] != null) {
    if (t[i].username.trim().equals(user)) {
    t[i].userAway = true;
    private void setClientAsBack(String user) {
    //this.userAway = false;
    //this.userBusy = false;
    //this.userInvisible = false;
    for (int i = 0; i < MAX_CONNECTIONS; i++) {
    if (t[i] != null) {
    if (t[i].username.trim().equals(user)) {
    t[i].userAway = false;
    t[i].userBusy = false;
    t[i].userInvisible = false;
    private boolean isUserBusy(String user) {
    boolean tmpIsBusy = false;
    for (int i = 0; i < MAX_CONNECTIONS; i++) {
    if (t[i] != null) {
    if (t[i].username.trim().equals(user)) {
    if (t[i].userBusy) {
    tmpIsBusy = true;
    break;
    } else {
    break;
    return tmpIsBusy;
    private boolean isUserInvisible(String user) {
    boolean tmpIsInvisible = false;
    for (int i = 0; i < MAX_CONNECTIONS; i++) {
    if (t[i] != null) {
    if (t[i].username.trim().equals(user)) {
    if (t[i].userInvisible) {
    tmpIsInvisible = true;
    break;
    } else {
    break;
    return tmpIsInvisible;
    * Method will close the connection to the server.
    * It will also free up array location for any new connections
    private void close() {
    if (isConnected) {
    try {
    connection.close();
    isConnected = false;
    userValidated = false;
    System.out.println("User " + username + " has disconnected from the Pita Messenger server.");
    for(int i=0; i < MAX_CONNECTIONS; i++)
    if (t[i]==this) t[i]=null; // set array element to null so we can accept another
    // connection had we been maxed out
    } catch (IOException e) { }
    } // end pmClientHandler class
    Now finally for my problem...this all works EXACTLY as expected when I telnet to the server. My client GUI application has an issue though. When I want to send an IM to a particular user...the thread code above that listens for *DISPATCHIM* get's who the IM is to and what the message is in the following protocol format *DISPATCHIM to msg* and call the following private method:private void dispatchIM(String to, String m) {
    for (int i = 0; i < MAX_CONNECTIONS; i++) {
    if (t[i] != null) {
    if (t[i].username.trim().equals(to)) {
    pmClientHandler x = t[i];
    PrintStream ps = x.sender;
    ps.println("IMMSG "+this.username+" "+m);
    Basically, if not obvious, what I'm doing here is iterating through the array of client connection threads and finding the client thread that belongs who this message is to, and accessing the sender object and dispatching to the IM to that client. Again, all works perfectly in telnet. However, my client GUI is not recieving any data. With all my testing, it seems that I am only able to access and modify strings and boolean variables, however it's like I've lost the sender object (only in my GUI app). This is really bugging the hell out of me and I've spent days trying to figure this out. Something is just not right. My client app has a dispatcher thread that constantly listens for incoming connects (if a buddy is online, or an instant message). This is the run method of that class:public void run() {
    String data;
    while(true) {
    try {
    try {
    data = reciever.nextLine();
    if (!data.trim().toUpperCase().startsWith("YES") && !data.trim().toUpperCase().startsWith("NO") && !data.trim().toUpperCase().startsWith("X") && !data.trim().toUpperCase().startsWith("Z")) {
    System.out.println("Foreign command: "+data);
    } catch (Exception e) { System.out.println("ERR: "+e); break; }
    // pass any data returned at any time during to the serverListener method
    serverListener(data);
    } catch (Exception e) { }
    * Method is used to handle all incoming messages from the server.
    private void serverListener(String data) {
    if (data.trim().toUpperCase().startsWith("IMMSG")) {   // Handle incoming im
    String imStr = data.substring(1).trim();
    String imFrom = imStr.substring(0,imStr.indexOf(" ")).trim();
    String imMsg = imStr.substring(imStr.indexOf(" ")).trim();
    // Check to see if we have any IM sessions open already
    if (isChatWithBuddyOpen(imFrom)) {
    imWindow thisIMSession = getIMSession(imFrom);
    thisIMSession.appendBuddyMessage(imMsg);
    thisIMSession.setVisible(true);
    } else {
    newIMSession(imFrom);
    imWindow thisIMSession = getIMSession(imFrom);
    thisIMSession.appendBuddyMessage(imMsg);
    thisIMSession.setVisible(true);
    // Garbage collection for old IM sessions
    if (!imSessions.isEmpty()) {
    for (int i = 0; i < imSessions.size(); i++) {
    imWindow isGarbageIM = imSessions.get(i);
    if (isGarbageIM == null || isGarbageIM.chatBuddy.trim().equals("")) {
    imSessions.remove(i);
    } else if (data.trim().toUpperCase().startsWith("Z")) {  // Handle user is away response
    String userResponse = data.substring(1).trim();
    clientGUI.handleUserAwayMsg(userResponse, true);
    } else if (data.trim().toUpperCase().startsWith("X")) {  // Handle user is online response
    String userResponse = data.substring(1).trim();
    clientGUI.handleUserAwayMsg(userResponse, false);
    } else if (data.trim().toUpperCase().startsWith("ISBUSY")) { // Handle user is busy response
    } else if (data.trim().toUpperCase().startsWith("NOTBUSY")) { // Handle user is not busy
    } else if (data.trim().toUpperCase().startsWith("ISINVISIBLE")) { // Handle user is invisible
    } else if (data.trim().toUpperCase().startsWith("NOTINVISIBLE")) { // Handle user is  not invisible
    } else if (data.trim().toUpperCase().startsWith("YES")) {  // Handle user is online
    String userResponse = data.substring(3).trim();
    clientGUI.handleUserOnlineMsg(true,userResponse);
    } else if (data.trim().toUpperCase().startsWith("NO")) {  // Handle user is offline
    String userResponse = data.substring(3).trim();
    clientGUI.handleUserOnlineMsg(false,userResponse);
    } // end serverListener method
    It's like my receiver object gets NOTHING. Again, this only occurs with my GUI app, in telnet. Can anyone PLEASE advise as to what might be occuring. Thanks very much. If you might really be able to help I could post the entire app and server zipped up so that you can poke through. If you help me figure this out and I understand why it's not working, I'll buy you a case of your favorite beer ;) Thanks!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                

    A couple of things.
    In future Networking related questions should be posted into the Networking forum.
    There is too much code here and too much page width. It's a bit overwhelming. You'll need to narrow this down a bit. From looking so far I see some potential
    portocol related issues. Like the readLine. Are you sure you are always writing line breaks on the other side? And then there's the substring bits which are
    going to be brittle.
    My suiggestion would be to trace things through and be able to point out exactly where the code is getting stuck/failing. Even getting it narrowed down to a method
    would be very helpful.

  • Server socket programming

    Hello
    I have my MultiThreaded java server running.
    It works fine if it gets continuously client request But
    client request comes after some period of time,
    my server does not respond back.
    My server is running through DOS window, so if I click
    enter there, then it gives response.I dont know what is the problem.
    Here is my server code.
    package com.venable.superpages;
    import java.io.*;
    import java.net.*;
    import java.lang.*;
    public class MapServer {
    public static long totalSystemTime = 0;
    public static void main(String args[]) {
              boolean DEBUG = true;;
              int port = 5003;
              int count = 0;
              ServerSocket welcomeSocket = null;
              try {
                   welcomeSocket = new ServerSocket(port);
                   if (DEBUG)
                        System.out.println("MapServer : main :" +
                        "Main thread about to start ");     
              } catch (IOException e) {
                   System.err.println("MapServer: main : Could not open socket");
              while (true) {
                   try {
                        Socket socket = welcomeSocket.accept();
                        socket.setKeepAlive(true);
                        socket.setSoTimeout(480000);
                        long startTime = System.currentTimeMillis();
                        System.out.println("Mapserver thread start time " +startTime);
                        MapServerThread serverThread = new MapServerThread(socket,startTime);
                        if (DEBUG)
                             System.err.println("Mapserver : main : thread about to start ");
                        count++;
                        if (DEBUG)
                             System.err.println("MapServer : main :count " + count);
                        serverThread.start();
                   } catch (IOException e) {
                        System.err.println("IO Error");
    this the thread :-
              public MapServerThread(Socket socket, long time) {
                   this.clientSocket = socket;     
                   requestStartTime = time;
              public void run() {
                   System.out.println( "connecting to server");
                   try {
                        inStream = new DataInputStream(clientSocket.getInputStream());
                        outStream = new DataOutputStream (clientSocket.getOutputStream());
                        byte[] len = new byte[6];
                        while(true){
                                  inStream.readFully(len);
                                  length = Integer.parseInt(new String(len));     
                                  if(length == 0){
                                       System.out.println(" breaking the while loop becuase of socket time out");
                                       break;
                                  length = length +0; // to remove leading zeroes.
                                  System.out.println( "length="+length);
                                  byte[] data = new byte[length];
                                  inStream.readFully(data);
                                  inputParam = new String(data);
                             if(length == 3){    // means left or right on the map special
                                  System.out.println( "LENGTH IS 3");
                                  getMapStatus(inputParam);
                                  if(type.equals("01") ){
                                       getMap();
                                  } else{
                                       getDirectionMap();
                             }else{
                                  parseInputParameter(inputParam);
                                  getLocationPoints(toFrom);
                   }catch(EOFException ex){
                        System.out.println( "Here EOF Exception");
                        try{
                             outStream.close();
                             inStream.close();
                             clientSocket.close();
                        }catch( Exception e){
                   }catch(Exception e){
                        System.out.println( "Here general Exception");
                        try{
                             outStream.writeBytes(servererror);
                             outStream.close();
                             inStream.close();
                             clientSocket.close();
                        }catch(Exception ex){
                   }

    What you need to do is just call read(). This will block and only return when there's some data on the socket. At that point, call socket.(getInputStream()).available() to find out how much data there is, and create new byte[] (or char[]) and read the available bytes

  • Socket Programming and Applets

    Hello Everyone,
    I am aiming to develop an application that would communicate with an Applet. I would like to know if this is possible and if there would be any security restrictions in between?
    Thank you

    you were running that your own machine, and what about java permission? how to handle that? suppose i have just jre installed and all permission disabled, how will your signed jar will run, there are many more things have to be done in that context.
    for doing this one have to read a lot of things
    http://java.sun.com/docs/books/tutorial/security/tour1/step2.html
    no personal issue, just pointing out few area.
    regards
    Aniruddha

  • Should i create a client and a server socket in a same application

    Greetings,
    In which situation sould i have a server socket ? and in which situation should i have a client socket ?and in which situation should i have both?
    I 'm making a app. who receives info (like alarms ) from a automation machine and also that same app. as a scheduler who send commands according to dates to the automation machine.
    Now the automation machine is programmed like a socket tcp/ip server who is always on and the app. is a client.
    Every time there's an alarm the machine sends me the info and i put it in a mysql database.
    Every time there's an event programmed the app. sends a string to the machine.
    The question is that i can't maintain that socket always connected, Sometimes disconnets.
    I was thinking of making the change of creating in both sides a server and a client, so that, for example, in the app. the client woul d handle the event msgs and the server would accecpt connections with alarms from the automaition machine.
    Since i'm a newbie in Java could somebody give me some tips, please?
    Thanks

    Thanks Peter....
    But i already do that....
    I have a thread who handles the connection management.
    If by some reaseon the connection is lost the thread reconnects it.
    My problem is that sometimes it reconnects every second, and i loose info provided by the automatian machine.
    The best thing to have it would be a socket listener, but Java does have any.
    Is there any API that does a socket listener?

  • Communication between Windows 7 and Windows 8(and above) using Sockets(TCP and UDP)

    I need to use TCP and UDP using Sockets to communicate between two(or more) applications installed in Windows 7 and Windows 8.
    Is it possible.? I tried within a LAN, but in vain. If needed I would post the appropriate code.
    Note: I only tried running exe(s) in these machines and not with installation.

    Hello Prabodh.Minz,
    >>Is it possible.?
    It is not clear what develop language you are using, here are examples which uses the C# based on .NET. It created the communition between two machines by using sockets with TCP protocol, a server and a client:
    Synchronous example:
    Client and
    Server.
    Asynchronous example:
    Client and
    Server.
    Multi-client per one server - socket programming in .net(C#)
    >>Note: I only tried running exe(s) in these machines and not with installation.
    There are all .exe.
    Regards.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Client Server Socket With GUI

    Hi,
    As the name of the forum suggests I am very new to this whole thing.
    I am trying to write a client/server socket program that can encrypt and decrypt and has a GUI, can't use JCE or SSL or any built in encryption tools.
    I have the code for everything cept the encryption part.
    Any help, greatly appreciated,

    tnks a million but how do i incorporate that into the following client and server code:
    here's the client code:
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketClient extends JFrame
              implements ActionListener {
    JLabel text, clicked;
    JButton button;
    JPanel panel;
    JTextField textField;
    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    SocketClient(){ //Begin Constructor
    text = new JLabel("Text to send over socket:");
    textField = new JTextField(20);
    button = new JButton("Click Me");
    button.addActionListener(this);
    panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.setBackground(Color.white);
    getContentPane().add(panel);
    panel.add("North", text);
    panel.add("Center", textField);
    panel.add("South", button);
    } //End Constructor
    public void actionPerformed(ActionEvent event){
    Object source = event.getSource();
    if(source == button){
    //Send data over socket
    String text = textField.getText();
    out.println(text);
         textField.setText(new String(""));
    //Receive text from server
    try{
         String line = in.readLine();
    System.out.println("Text received :" + line);
    } catch (IOException e){
         System.out.println("Read failed");
         System.exit(1);
    public void listenSocket(){
    //Create socket connection
    try{
    socket = new Socket("HUGHESAN", 4444);
    out = new PrintWriter(socket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (UnknownHostException e) {
    System.out.println("Unknown host: HUGHESAN.eng");
    System.exit(1);
    } catch (IOException e) {
    System.out.println("No I/O");
    System.exit(1);
    public static void main(String[] args){
    SocketClient frame = new SocketClient();
         frame.setTitle("Client Program");
    WindowListener l = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.addWindowListener(l);
    frame.pack();
    frame.setVisible(true);
         frame.listenSocket();
    SERVER Code
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketServer extends JFrame
              implements ActionListener {
    JButton button;
    JLabel label = new JLabel("Text received over socket:");
    JPanel panel;
    JTextArea textArea = new JTextArea();
    ServerSocket server = null;
    Socket client = null;
    BufferedReader in = null;
    PrintWriter out = null;
    String line;
    SocketServer(){ //Begin Constructor
    button = new JButton("Click Me");
    button.addActionListener(this);
    panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.setBackground(Color.white);
    getContentPane().add(panel);
    panel.add("North", label);
    panel.add("Center", textArea);
    panel.add("South", button);
    } //End Constructor
    public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    if(source == button){
    textArea.setText(line);
    public void listenSocket(){
    try{
    server = new ServerSocket(4444);
    } catch (IOException e) {
    System.out.println("Could not listen on port 4444");
    System.exit(-1);
    try{
    client = server.accept();
    } catch (IOException e) {
    System.out.println("Accept failed: 4444");
    System.exit(-1);
    try{
    in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    out = new PrintWriter(client.getOutputStream(), true);
    } catch (IOException e) {
    System.out.println("Accept failed: 4444");
    System.exit(-1);
    while(true){
    try{
    line = in.readLine();
    //Send data back to client
    out.println(line);
    } catch (IOException e) {
    System.out.println("Read failed");
    System.exit(-1);
    protected void finalize(){
    //Clean up
    try{
    in.close();
    out.close();
    server.close();
    } catch (IOException e) {
    System.out.println("Could not close.");
    System.exit(-1);
    public static void main(String[] args){
    SocketServer frame = new SocketServer();
         frame.setTitle("Server Program");
    WindowListener l = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.addWindowListener(l);
    frame.pack();
    frame.setVisible(true);
         frame.listenSocket();
    Again help on this is very welcomed

  • Server Socket Help!

    Hello!
    I have a problem regarding server socket, i wrote a simple server socket program which would accept a socket then write through the DataOutputStream, using writeByte and read through the DataInputStream using readUnsignedByte.
    My server socket is a java program, and the client was created using other language (which i do not know what language but it is already existing..).
    My concern is that when I try to listen (in the server side), i would accept the socket, and the connection would now be established. BUT, whenever i would close my streams (input and output stream), the client socket I accepted and the ACTUAL server socket, the client is still connected. That's why whenever i would open my Server Socket, i would no longer receive any socket.. why is it like that..?
    Can anyone help me..? Please do so.. I would appreciate your immediate reply..
    Thanks a lot!
    Ron

    HI,
    What you need in the client app is for it to listen for a CLOSE message like this (java code but the logic is there)
    String fromServer ;
    while(( fromServer = in.readLine()) != null )
    System.out.println( "Server: " + fromServer ) ;
    if( fromServer.equals("Closing down")) //checks all the time for the CLOSE signal !
    break ;
    // other stuff
    out.close() ; // close the client end of the socket on the signal !
    in.close() ;
    You say the client app is already written. Well look in the specs and see what the CLOSE signal is.
    There MUST be one or the client app doesn't work.
    Hope that helps,

  • SOCKET PROGRAMMING  HELP NEEDED!!!!

    hi,
    I got an idea of establishing socket connection with all clients from SERVER through the windows command
    called (arp -a). when we type the stated command on dosprompt in server, it gives the list of current system's
    ipaddress.....switched on. SO i can establish socket connections in a for loop where i can take the following ipaddress from output listed from command.
    i've written the code to call the command in JAVA.
    i write the dosprompt output in a file named list1.txt
    import java.util.*;
    import java.io.*;
    import java.io.File;
    public class RunCommand
    public static String[] runCommand(String cmd) throws IOException
    ArrayList list = new ArrayList();
    Process proc = Runtime.getRuntime().exec(cmd);
    InputStream istr = proc.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(istr));
    String str;
    while ((str = br.readLine()) != null)
    list.add(str);
    try
    proc.waitFor();
    }catch (InterruptedException e)
    System.err.println("process was interrupted");
    // check its exit value
    if (proc.exitValue() != 0)
    System.err.println("exit value was non-zero");
    // close stream
    br.close();
    // return list of strings to caller
    return (String[])list.toArray(new String[0]);
    public static void main(String[] args) throws Exception
    try
    FileWriter f1=new FileWriter("list1.txt");
    String[] s = runCommand("arp -a");
    for (int i = 0; i< s.length; i++)
    f1.write(s);
    System.out.println(s[i]);
    f1.close();
    }catch (Exception ex) { System.out.println(ex);}
    SAMPLE OUTPUT:
    Interface: 172.16.3.1 on Interface 0x1000003
    Internet Address Physical Address Type
    172.16.3.4 00-00-e2-13-a9-e8 dynamic
    172.16.3.6 00-00-e2-13-aa-0f dynamic
    172.16.3.10 00-00-e2-13-ab-bb dynamic
    172.16.3.12 00-00-e2-13-ab-93 dynamic
    172.16.3.16 00-00-e2-13-37-b8 dynamic
    172.16.3.17 00-00-e2-13-37-19 dynamic
    172.16.3.18 00-00-e2-13-37-1d dynamic
    172.16.3.19 00-00-e2-13-38-98 dynamic
    172.16.3.22 00-00-e2-13-37-54 dynamic
    172.16.3.23 00-00-e2-13-39-02 dynamic
    172.16.3.24 00-00-e2-13-39-0f dynamic
    172.16.3.26 00-00-e2-13-37-a5 dynamic
    172.16.3.27 00-00-e2-13-37-0b dynamic
    172.16.3.28 00-00-e2-13-37-12 dynamic
    172.16.3.29 00-00-e2-13-39-15 dynamic
    172.16.3.30 00-00-e2-13-38-af dynamic
    172.16.3.31 00-00-e2-13-37-fe dynamic
    172.16.3.32 00-00-e2-13-38-ff dynamic
    172.16.3.34 00-00-e2-13-ab-c8 dynamic
    172.16.3.37 00-00-e2-13-ab-67 dynamic
    172.16.3.42 00-00-e2-13-ab-19 dynamic
    PLS HELP ME OUT IN GETTING ONLY THE IPADDRESS IN FOR LOOP IN SERVER SOCKET PROGRAM TO INVOKE ALL CLIENT'S PROGRAM IN NETWORK.
    PLS HELP ME!!!!!!!
    ATTACH THE CODE!!!!!!!!!!!!

    Connecting to a client presumes that the client is waiting for a connection.
    If that is the case I would suggest looking a java.net.Socket.

  • Implementing sockets and threads in a jframe gui program

    Hi, I am trying to find a solution to a problem I am having designing my instant messenger application.
    I am creating listening sockets and threads for each client logged into the system. i want to know if there is a way to listen to other clients request from the main gui and then if another client tries to establish a connection with me for example, a thread is created for that client and then my chat gui opens automatically has soon has the other client sends his or hers first text message to me.
    I am relatively new at socket programming has I am currently studying along this area. I know how to create threads and sockets but I am having trouble finding out a solution to my problem. Here is the code that I have done so far for the listening method from my main gui, and the thread class of what I have done so far.
    listening socket:
         private void listeningSocket()
                ServerSocket serverSocket = null;
                boolean listening = true;
                try
                    //listen in port 4444;
                    serverSocket = new ServerSocket(4444);
                catch(IOException x)
                    JOptionPane.showMessageDialog(null, "cannot listen to port 4444", null, JOptionPane.ERROR_MESSAGE);
                while(listening)
                    client_thread w;
                    try
                       w = new client_thread(serverSocket.accept(), jTextArea1);
                       Thread t = new Thread(w);
                       t.start();
                    catch(IOException x)
                         JOptionPane.showMessageDialog(null, "error, cannot start new thread", null, JOptionPane.ERROR_MESSAGE);
            }thread class:
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.sql.*;
    import java.awt.event.*;
    * @author jonathan
    public class client_thread extends Thread
         //define new socket object
        private Socket client_user = null;
        private JTextArea textArea;
        public client_thread(Socket client_user, JTextArea textArea)
            this.client_user = client_user;
            this.textArea = textArea;
        public void run()
            BufferedReader in = null;
            PrintWriter out = null;
            String error = "error has occured, messege was not sent";
            String messege = null;
             try
                //create input and output streams
                in = new BufferedReader(new InputStreamReader (client_user.getInputStream()));
                out = new PrintWriter(client_user.getOutputStream(), true);
                while(true)
                   //read messege sent by user
                   messege = in.readLine();
                    //display messege in textfield
                   out.println(messege);
                   textArea.append(messege);
            catch (IOException e)
                //error messege
                JOptionPane.showMessageDialog(null, error, null, JOptionPane.ERROR_MESSAGE);
    }

    Seems like all you need to do is create a new dialog for each socket that is established. Your current design looks like it will attempt to use the same textarea for all the sockets.
    I would say in your thread class do the following:
    MyConversationDialog dialog = new MyConversationDialog();
    while(true)
                   //read messege sent by user
                   messege = in.readLine();
                    //display messege in textfield
                   out.println(messege);
                   dialog.setVisible (true);
                   dialog.addMessage (message);
                }

  • How to run a datagram socket client and server program

    hi,
    I am new to socket programming. I am following the tutorial of sun for socket programming...The link is
    http://java.sun.com/docs/books/tutorial/networking/datagrams/clientServer.html
    I have understood the concept, but the problem is i cannot run the program. I am using netbeans and i have created a package and stored the files QuoteServer,QuoteServerThread, QuoteClient in this package. How can i make the server program run first and then client program in netbeans
    kindly help me
    Thankyou

    I think you are trying to run both server and client
    on one machine!!!
    It is impossible, your server is blocking the port to
    send packets, so you must run client on another
    computer!!!It's not impossible to run a client and server on the same machine just for testing or as a demo. Just have the server listen on one port and the client use a different port.
    No need to use 2 seperate computers. I've done it one computer before without a problem.
    Nick

  • Socket and Thread Explanation

    I'm a little confused on the Socket stuff. I read some tutorials but wanted to make sure I understand. I'm using a simple client/server chat app as a reference.
    First the ServerSocket is just a connection to the port you want to listen on... I understand that. Is the Sockets... Socket s = ss.accept(); a tunnel to the port for data to travel on?
    Second.. When you create a Thread. This is the information that travels on these sockets? If that's the case I understand... But I have one question relating to some chat code I can't quite figure out.
    The simple chat program conists of a ChatServer, ServerThread and a Client.
    in the ChatServer it creates a ServerSocket and later on it looks for new connections for clients and then creates a ServerThread. What the heck is this for. From the code in the ServerThread it just handles incoming data and sends them back out. OK.
    But in the Client... it connects to this port and then creates it's own thread i.e. new Thread(this).start();
    Why ServerThread and then a Thread from the Client... Shouldn't there just be one?
    Sorry, I just can't get this.

    I'm a little confused on the Socket stuff. I read
    some tutorials but wanted to make sure I understand.
    I'm using a simple client/server chat app as a
    reference.
    First the ServerSocket is just a connection to the
    port you want to listen on... I understand that. Is
    the Sockets... Socket s = ss.accept(); a tunnel to
    the port for data to travel on?when the accept() method called, the server socket will start listening to the port for any connection. Once a connection established, this method will return a connected socket.
    >
    Second.. When you create a Thread. This is the
    information that travels on these sockets? If that's
    the case I understand... But I have one question
    relating to some chat code I can't quite figure out.A new thread was created here to that this thread can handle the socket return by the serversocket independenty to the main thread. Mainly server code will do this so that the main thread can continue to listening to other new connection agains while this newly created thread will handle any communication between a connected client and server.
    The simple chat program conists of a ChatServer,
    ServerThread and a Client.
    in the ChatServer it creates a ServerSocket and later
    on it looks for new connections for clients and then
    creates a ServerThread. What the heck is this for.
    From the code in the ServerThread it just handles
    incoming data and sends them back out. OK.
    But in the Client... it connects to this port and then
    creates it's own thread i.e. new Thread(this).start();Well, i dun know how the code for the client look like... but guessing that the client was implements Runnable. So, in the main method, it spawn a new thread and pass this class for this new thread to handle while the main thread maybe continue to do other things or just end after finish.
    >
    Why ServerThread and then a Thread from the Client...
    Shouldn't there just be one?
    Sorry, I just can't get this.Well, hope my explaination was clear enough... :P

Maybe you are looking for