new socket created for each message sent.! help!
i have made a client application and a server application. the server application is made to listen for requests on port 9090 on loop back ip = 127.0.0.1. the client is like a chat programm sending messages. the server receives this message and is supposed to sent it back to the client and only then is the client supposed to dispaly it in the message history. the program runs fine with multiple clients also but there is a weird problem.
instead of having one socket object per connection it is creating a socket object each time 'send' is clicked in the client. and this is clearly not what i want as it would create problems in future when i make two clients talk to each other. here is the server code split accross two classes. class Server and class SocketHandler.
//a server that can receive and send data to client.
package server;
import java.io.*;
import java.net.*;
class Server
{
publicstaticvoid main(String[] args)
{
try
{
ServerSocket ss =new ServerSocket(9090);//Opens a new ServerSocket.
while(true)//Listens endlessly for a socket connection
{
Socket sc = ss.accept();// returns a socket object when connection is requested by the client.
//Creates a new SocketHandler object, passes the referrence of the socket object as an argument to its constructor and attaches a new thread to work on it.
new Thread(new SocketHandler(sc)).start();
}
}
catch(IOException e)
{
System.out.println("IOException. Cannot initialize server");
}
}
}
package server;
import java.io.*;
import java.net.*;
class SocketHandlerimplements Runnable
{
Socket soc;// handle to refer a socket object.
// variable to count number of socket objects created depenging on number of time constructor invoked
staticint i =0;
SocketHandler(Socket sc)//constructor to accept handle to a socket object.
{
soc = sc;//assign the handle of socket object to instance variable soc.
i++;//increments socket count.
System.out.println(i);//display the number of the socket connection.
}
publicvoid run()
{
try
{
//define in object to accept string.
BufferedReader in =new BufferedReader(new InputStreamReader(soc.getInputStream()));
//define out object to send a string.
PrintWriter out =new PrintWriter(new BufferedWriter(new OutputStreamWriter(soc.getOutputStream())),true);
while(true)//runs as long as client doesnot close the connection.
{
String str = in.readLine();//receive message from client.
out.println(str);//send it back to client.
}
}
catch(IOException e)
{
System.out.println("IO Exception");
}
}
}

