Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Client/Server problem 1

Status
Not open for further replies.

vcllvc

Programmer
Jul 12, 2001
136
US
I'm trying to write a simple multi thread server. My approach is when server.accept() return a socket, create a thread to handle the streams. The problem is when I run the clients code, the first client is able to communicate with the server. After that, both other clients and the server seem to be waiting forever.

Pls, help me figure it out the problem. Thx.

THIS IS THE SERVER CODE:

package networking;
import java.net.*;
import java.io.*;

public class NetWorking extends Thread{
Socket clientConnection;
ServerSocket server;

NetWorking(){

try {

server=new ServerSocket(80);
while(true){
clientConnection=server.accept();


start();
}

}catch(UnknownHostException e) {
System.out.println (e.getMessage());
}catch(IOException e){
e.printStackTrace();
}

}

public void run(){
try{
DataOutputStream outStream=new DataOutputStream(clientConnection.getOutputStream());
DataInputStream inStream=new DataInputStream(clientConnection.getInputStream());

outStream.writeUTF("Server message: Hello");
System.out.println(inStream.readUTF() );

System.out.println("Client connection is closing");
clientConnection.close();

}catch(IOException e){
e.printStackTrace();
}

}


static public void main(String[] args){

NetWorking server=new NetWorking();


}

}




THIS IS THE CLIENT CODE:

package networking;
import java.net.*;
import java.io.*;

class Client {

public Client(){
try{
Socket clientServer=new Socket(InetAddress.getLocalHost(), 80);
DataOutputStream outStream=new DataOutputStream(clientServer.getOutputStream());
DataInputStream inStream=new DataInputStream(clientServer.getInputStream());

System.out.println(inStream.readUTF());
outStream.writeUTF("Client message: CLIENT REQUEST ACCESS");

System.out.println("Client is closing");
clientServer.close();

}catch (UnknownHostException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}


}


static void main(String[] args){
Client c=new Client();
}

}
 
hi

there's a problem with ur server code. after accept method, u must create a new socket (not serversocket), and hand over the client connection to that socket. only then ur server socket will b free for the other clients. i've done a chat program like this and it works fine. feel free to contact me if u r in need of help.

luv
Karthik.
 
Thanks a lot. It's very helpful. Thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top