473,407 Members | 2,359 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

Java Chat Server takes up 100% of CPU w/ 2 cnxns? Please help me find whats wrong

I am making this pretty basic chat project, and I found this echo server on the internet and decided to modify it my needs (much of the methods and fields are the same).

Basically what my program does is acts like a chat room. One computer runs the server which other java programs connect to and can communicate with one another. The problem is that this server I run is horribly inefficient.

I had to use 2 threads for each connection because one thread needs to continuously listen for incoming messages and the other has to send out messages for other computers. If i put them in the same thread the one that listens for messages will block the line for sending messages.


Expand|Select|Wrap|Line Numbers
  1. import java.net.*;
  2. import java.io.*;
  3.  
  4. public class EchoServer
  5. {        
  6.     ServerSocket m_ServerSocket;
  7.     private int counter=0;
  8.     private String global_message = "first line";
  9.  
  10.     public EchoServer() 
  11.     {
  12.         try
  13.         {
  14.             m_ServerSocket = new ServerSocket(8008);
  15.         }
  16.         catch(IOException ioe)
  17.         {
  18.             System.out.println("Could not create server socket at 8008. Quitting.");
  19.             System.exit(-1);
  20.         }
  21.  
  22.         System.out.println("Port Created on 8008");
  23.         int id = 0;
  24.         while(true)
  25.         {                        
  26.             try
  27.             {
  28.                 Socket clientSocket = m_ServerSocket.accept();
  29.                 ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
  30.                 ClientListner lisThread = new ClientListner(clientSocket, id++);
  31.                 cliThread.start();
  32.                 lisThread.start();
  33.             }
  34.             catch(IOException ioe)
  35.             {
  36.                 System.out.println("Exception encountered on accept. Ignoring. Stack Trace :");
  37.                 ioe.printStackTrace();
  38.             }
  39.         }
  40.     }
  41.  
  42.     public static void main (String[] args)
  43.     {
  44.         new EchoServer();    
  45.     }
  46.  
  47.     class ClientListner extends Thread
  48.     {
  49.         Socket m_clientSocket;        
  50.         int m_clientID = -1;
  51.         boolean m_bRunThread = true;
  52.  
  53.         ClientListner(Socket s, int clientID)
  54.         {
  55.             m_clientSocket = s;
  56.             m_clientID = clientID;
  57.         }
  58.  
  59.         public void run()
  60.         {            
  61.             BufferedReader in = null; 
  62.             PrintWriter out = null;
  63.             PrintWriter tempout = null;
  64.             System.out.println("Accepted Client : ID - " + m_clientID + " : Address - " + 
  65.                              m_clientSocket.getInetAddress().getHostName());
  66.  
  67.             try
  68.             {                                
  69.                 in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
  70.                 while(m_bRunThread)
  71.                 {                    
  72.                     String tempitoo = in.readLine();
  73.                     if (!(tempitoo==null))
  74.                     {
  75.                     global_message = tempitoo;
  76.                        }
  77.  
  78.                     System.out.println("Client Says :" + global_message);
  79.  
  80.  
  81.                     if(global_message.equalsIgnoreCase("close"))
  82.                     {
  83.                         m_bRunThread = false;   
  84.                         System.out.print("Stopping client thread for client : " + m_clientID);
  85.                     }
  86.                     else
  87.                     {}
  88.                 }
  89.             }
  90.             catch(Exception e)
  91.             {
  92.                 e.printStackTrace();
  93.             }
  94.             finally
  95.             {
  96.                 // Clean up
  97.                 try
  98.                 {                    
  99.                     in.close();
  100.                     out.close();
  101.                     m_clientSocket.close();
  102.                     System.out.println("...Stopped");
  103.                 }
  104.                 catch(IOException ioe)
  105.                 {
  106.                     ioe.printStackTrace();
  107.                 }
  108.             }
  109.         }
  110.     }    
  111.     class ClientServiceThread extends Thread
  112.     {
  113.         Socket m_clientSocket;        
  114.         int m_clientID = -1;
  115.         boolean m_bRunThread = true;
  116.  
  117.         ClientServiceThread(Socket s, int clientID)
  118.         {
  119.             m_clientSocket = s;
  120.             m_clientID = clientID;
  121.         }
  122.  
  123.         public void run()
  124.         {            
  125.             BufferedReader in = null; 
  126.             PrintWriter out = null;
  127.             PrintWriter tempout = null;
  128.             String clientCommand = "user: allo";
  129.             try
  130.             {                                
  131.                 out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream()));
  132.                                             out.println("test");
  133.                             out.flush();
  134.  
  135.                 while(true)
  136.                 {              
  137.  
  138.                     if (!clientCommand.equals(global_message))
  139.                     {
  140.                             clientCommand = global_message;
  141.                             out.println(global_message);
  142.                             out.flush();
  143.                             System.out.println("Message Sent");
  144.  
  145.                     }
  146.                 }
  147.             }
  148.             catch(Exception e)
  149.             {
  150.                 e.printStackTrace();
  151.             }
  152.             finally
  153.             {
  154.                 try
  155.                 {                    
  156.                     in.close();
  157.                     out.close();
  158.                     m_clientSocket.close();
  159.                     System.out.println("...Stopped");
  160.                 }
  161.                 catch(IOException ioe)
  162.                 {
  163.                     ioe.printStackTrace();
  164.                 }
  165.             }
  166.         }
  167.     }
Feb 17 '08 #1
1 1725
I found out what is causing all my problems but I dont know how to fix it... it is in the ClientServiceThread Class of my code, where the while loop scans the global message continuously to see if it has changed.

Any ideas?
Feb 17 '08 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Wendy S | last post by:
We've been provided a Java app to use for a homework assignment on databases. It's my own fault for writing inefficient queries, but it keeps taking 100% of my CPU and it takes several minutes to...
4
by: techy techno | last post by:
Hii I am trying to write down a cdont aplication which will email the survey form to the TO address with the answers checked by the user using the survey form I am 100% sure that there is...
2
by: Paul | last post by:
Hello, I nead to create chat server but i cannot find any sample can you show me how i can craete multirhread chat server. ?? Regards PM
3
by: nahiyan13 | last post by:
hey there I have been given a problem where i have to write a function integerPower(base,exponent)that returns the value base^exponent(in words meaning if base is 2 and exponent is 3 then the...
4
by: Ronald Green | last post by:
Hi, I have this theoretical problem: Say that I need a chat server that also has a database where it saves all conversations. However, I need several servers for availability and load balancing....
1
by: jigar.0508 | last post by:
Hi friends. I am developing online communication application which contains the features like chat,audio,video, data transfer etc. I am actually in final year and developing a project. For...
1
by: x40 | last post by:
I try to learn python thru solving some interisting problem, found google trasure hunt, write first program ( but cant find whats wrong). # Unzip the archive, then process the resulting files to...
7
by: shathaaaa | last post by:
hi every body here i try to run program written in java (client server chat Application ) but when i try to compile it i get this error " RMIChatServerImpl.java.java:6: calss,interface,or...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.