• Post Reply Bookmark Topic Watch Topic
  • New Topic

problem with my threading  RSS feed

 
Chris Dancy
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have a problem running a server, that accepts multiple users for a chat client. It accpets more than one person, but only one person gets to type anything. here is the code If anyone can tell me whats wrong that'd be great.

import java.io.*;
import java.net.*;
public class SimpleThreadedServer3
{
static final int portNumber = 5095;
private ServerSocket ss;
private InetAddress addr;
private PrintWriter writer;
private String messageIn,messageOut;
private BufferedReader reader;
public static void main(String [] args)
{
new SimpleThreadedServer3().initiateStartUp();
}
public void initiateStartUp()
{
try{
addr = InetAddress.getLocalHost();

System.out.println("Creating Server Socket at:"+portNumber+" . . . ");
System.out.println("At Host:"+ addr.getHostName()+" . . .");
System.out.println("At Address:"+ addr.getHostAddress()+" . . .");
ss = new ServerSocket(portNumber);

System.out.println("System Online ...");
while(true)
{
Socket sock = ss.accept();
writer = new PrintWriter(sock.getOutputStream());
System.out.println(sock+ "I am a white man");
String m = "stinky";
writer.println(m);

new Thread(new ClientHandler(sock)).start();
}

}catch(IOException e)
{
System.out.println(e);
}
}
class ClientHandler implements Runnable
{
private Socket sock;
public ClientHandler(Socket s)
{
try{
sock = s;

reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
System.out.println(reader+"stinky bear");
String messageIn;
while((messageIn = reader.readLine())!=null)
{
System.out.println(messageIn);
writer.println(messageIn);
}
}catch(Exception e)
{
System.out.println(e);
}
}
public void run()
{
String messageOut;
try{
while((messageOut = reader.readLine())!= null)
{
System.out.println(messageOut);
sendToAll(messageOut);
}
}catch(Exception e)
{
System.out.println(e);
}
}
}
public void sendToAll(String messageOut)
{
try{
writer.println(messageIn);
writer.println(messageOut);
writer.flush();
}catch(Exception e)
{
System.out.println(e);
}
}
}
 
Yuan Ye
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The bug is that your "writer" and "reader" varible are at the class level of SimpleThreadedServer3, only a single instance per server. They are being reset everytime a new client obtains the socket. If you move these two varible to ClientHandler class level, it should solve this problem.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!