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.

Similar Messages

  • 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 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.

  • 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 usin nio package

    hello frens i m new to socket programming
    i come to know that nio packaage provides more sophisticated and efficient API to deal with socket programming issue
    I need to know where i can get tutorial about socket programming using nio pacakage

    Try google
    http://www.google.co.uk/search?q=java+nio+tutorial

  • 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

  • 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.

  • 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-Not getting response from server.

    Hi,
    I am trying to communicate with server using java socket programming, I am getting the response for first two times third time when I am trying to write some thing I am not getting any response from the server,
    I am writing to migrate the vb code to Java the vb is using a c++ dll to communicate with the server and we tried accessing the dll from java using JNI then it is working fine, this dll is dependent on windows so we want to avoid the dependency with windows that is why we are going for socket programming, Please help on this.

    Hi,
    I am writing the data in forms of string
    like
    Socket sockt = new Socket(ipAddress, portNo);     
    out= new DataOutputStream(sockt.getOutputStream());
    in = new DataInputStream(sockt.getInputStream());
    out.writeBytes("Serv");
    out.writeBytes("Serv,32");
    out.writeBytes("home,serv32,run.prg,sucess");
    these are the strings to communicate with server.
    I am trying to read the same
    StringBuffer buf = new StringBuffer();
              byte b = '\0';
                        try {
                   while ((b = in.readByte()) != '\0')
                        char ch = (char) b;
                        buf.append(ch);
              } catch (Exception e) {
                   System.out.println(e.getStackTrace());
    we are getting the response for the first two strings, but for the third string it is getting stucked for some time and returing some junk values like '???' we are sending the same string using JNI and it is working.

  • How to detect client socket shutdowns in server socket

    Hi,
    Hoping to get some help with this. I am writing this program that implements a socket server that accepts a single client socket (from a third-party system). This server receives messages from another program and writes them to the client socket. It does not read anything back from the client. However, the client (which I have no control over) disconnects and reconnects to my server at random intervals. My issue is I cannot detect when the client has disconnected (normally or due to a network failure), hence am unable to accept a fresh connection from the client. Here's my code for the server.
    ServerSocket serverSocket = null;
    Socket clientSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    try{
              if (serverSocket == null){
                    serverSocket = new ServerSocket(4511);
         clientSocket = serverSocket.accept();
         System.out.println("Accepted client request ... ");
         out = new PrintWriter(clientSocket.getOutputStream(), true);
         in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
         System.out.println("Input / Output streams intialized ...");          
         while (true){                              
              System.out.println("Is Client Socket Closed : " + clientSocket.isClosed());
              System.out.println("Is Client Socket Connected : " + clientSocket.isConnected());
              System.out.println("Is Client Socket Bound : " + clientSocket.isBound());
              System.out.println("Is Client Socket Input Shutdown : " + clientSocket.isInputShutdown());
              System.out.println("Is Client Socket Output Shutdown : " + clientSocket.isOutputShutdown());
              System.out.println("Is Server Socket Bound : " + serverSocket.isBound());
              System.out.println("Is Server Socket Closed : " + serverSocket.isClosed());
              messageQueue = new MessageQueue(messageQueueDir+"/"+messageQueueFile);
              //get Message from Queue Head (also removes it)
              message = getQueueMessage(messageQueue);
              //format and send to Third Party System
              if (message != null){
                             out.println(formatMessage(message));
                   System.out.println("Sent to Client... ");
              //sleep
              System.out.println("Going to sleep 5 sec");
              Thread.sleep(5000);
              System.out.println("Wake up ...");
    }catch(IOException ioe){
         System.out.println("initSocketServer::IOException : " + ioe.getMessage());
    }catch(Exception e){
         System.out.println("initSocketServer::Exception : " + e.getMessage());
    }I never use the client's inputstream to read, although I have declared it here. After the client is connected (it enters the while loop), it prints the following. These values stay the same even after the client disconnects.
    Is Client Socket Closed : false
    Is Client Socket Connected : true
    Is Client Socket Bound : true
    Is Client Socket Input Shutdown : false
    Is Client Socket Output Shutdown : false
    Is Server Socket Bound : true
    Is Server Socket Closed : false
    So, basically I am looking for a condition that detects that the client is no longer connected, so that I can bring serverSocket.accept() and in and out initializations within the while loop.
    Appreciate much, thanks.

    Crossposted and answered.

  • File descriptor leak in socket programming

    We have a complex socket programming client package in java using java.nio (Selectors, Selectable channel).
    We use the package to connect to a server.
    Whenever the server is down, it tries to reconnect to the server again at regular intervals.
    In that case, the number of open file descriptors build up with each try. I am able to cofirm this using "pfile <pid>" command.
    But, it looks like we are closing the channels, selectors and the sockets properly when it fails to connect to the server.
    So we are unable to find the coding that causes the issue.
    We run this program in solaris.
    Is there a tool to track down the code that leaks the file descriptor.
    Thanks.

    Don't close the selector. There is a selector leak. Just close the socket channel. As this is a client you should then also call selector.selctNow() to have the close take final effect. Otherwise there is also a socket leak.

  • Daemon and socket programming

    Hi,
    I have been given a new project whereby I have to:
    1) Write a class with a method that takes as an argument an xml document, communicate s with a SOAP server and return the SOAPs response (in this case a ResponseWrapper object).
    2) This then has to be implemented as a Daemon, that listens to a particular socket.
    The reason for this being is that it can be uploaded to a server, allowing a pearl program to send the XML to the Daemon, have this contact the SOAP server and then return the SOAPs response back to the pearl program.
    I am aware that this sounds unnecessarily complicated but it does have to be implemented this way.
    I have written the class and it successfully communicates with the SOAP server and returns a response, but have no idea how to implement it as a Daemon and have had no experience with socket programming.
    Could anyone point me to a tutorial or give me some pointers in how to get started?
    Thanks,

    It was an option to use a Web Service, but I was told
    that due to security issues it would take to long to
    write all the necessary checks and interceptors
    (which I know how to do), so I should implement it
    this way (which I don't know how to do); since it is
    sitting behind the firewall it would not be
    accessible for spoofing.Huh? You realize that tons of very sensitive information is transmitted all over the internet using Web Services right?
    I have had no experience
    with implementing this type of thing before, What is your level of experience then? This may be over your head. I'm not saying that sockets and daemons are advanced concepts, but I wouldn't throw a beginner into that task.

  • RESTFUL Web Services vs Socket Programming Performance

    Hi guys,
    I will have an application which will have a service serving about to 30 million users/day and a mean of 5 requests/user.
    It means that there will be about 150 million requests per day. I will have two servers behind a load balancer and my clients will be both Java and C++.
    I think to implement RESTFUL Web Services but afraid of performance issues.
    Did you have a knowledge about the performances of web service and socket programming in such a high loaded project?
    Tnx.
    Ayberk

    ayberkcansever wrote:
    Hi guys,
    I will have an application which will have a service serving about to 30 million users/day and a mean of 5 requests/user.
    It means that there will be about 150 million requests per day. I will have two servers behind a load balancer and my clients will be both Java and C++.
    I think to implement RESTFUL Web Services but afraid of performance issues.
    Did you have a knowledge about the performances of web service and socket programming in such a high loaded project?It depends on the CPUs, RAM, disks, and network configurations of those servers.
    It depends on how the requests are distributed throughout the day.
    It depends on how big the requests are and how big the responses are.

  • Simple client - proxy - server toy program

    Hi.
    I haven't done many cs courses yet, lately i am reading on some introduction to network programming, and i thought i should create a simple toy program to test a bit.
    Essentially i'd like to keep the communication between client and server using bytes, so i'll but input/output streams. At the same time, i'd like to have the proxy and server and client hosted on the same pc. So, i'll be using local IP's like 127.xx.xx.xx
    Client part:
    1. open a socket to connect to proxy
    2. get input and output streams
    3. use loop to write random data to output stream, and read feedbacks from inputstream.
    Proxy Part
    1. opens a server soc to listen to client
    2. opens a soc to connect to server
    3. create 2 service objects to take care of IO, one for upstream(to server) and other for downstream
    4. display and verify content.
    Server Part:
    1. open a server socket to listen to connections
    2. create a service object to take care of stream IO
    3. display IO streams to counter verify with client IO
    Questions:
    1. When constructing a socket for client side, i should be including proxy IP and proxy listened_port as parameters right?
    if I try to put in a local ip such as 127.99.99.99, and port number 5999. At the same time i set my proxy port_to_listen_to as 5999
    how will I know which address represents my proxy?
    Will any random local IP work?
    Will a thread be more appropriate since i am using threads in proxy and server?
    2. My understanding of proxy is that it is partly a server, and partly a client. But i am not sure if i am right to create 2 threads to handle upstream and downstream operations independently. I have tried to stay out of global/static variable so that i can avoid synchronization part.
    3. As for the server side. i have similar issues regarding the IP address problems mentioned above.
    Can some one help me sort out my concepts?

    1. When constructing a socket for client side, i should be including proxy IP and proxy listened_port as parameters right?Yes.
    if I try to put in a local ip such as 127.99.99.99, and port number 5999. At the same time i set my proxy port_to_listen_to as 5999
    how will I know which address represents my proxy?That address represents your proxy.
    Will any random local IP work?127.0.0.* will work. I don' t know about the others like 127.99.99.99.
    Will a thread be more appropriate since i am using threads in proxy and server?Only if you have multiple connections in the client at the same time, or if the client's input and output are unco-ordinated. From your description it sounds like you are writing requests and reading responses, which you can do serially without threads.
    2. My understanding of proxy is that it is partly a server, and partly a client. But i am not sure if i am right to create 2 threads to handle upstream and downstream operations independently.You are right.
    3. As for the server side. i have similar issues regarding the IP address problems mentioned above.I don't know exactly what you mean by 'issues' or 'problems'. You can run the whole setup using 127.0.0.1, or 'localhost', with one listening port for the proxy and another for the server.

Maybe you are looking for