Here's some sample code that I did for a simple client server test:
Code:
package alex.gw;
import java.util.*;
import java.net.*;
import java.io.*;
class Client
{
public static void main(String[] args)
throws Exception
{
Socket s;
//InetSocketAddress isa;
String string;
OutputStream os;
//isa=new InetSocketAddress("localhost", 5000);
//s=new Socket("localhost", 5000);
s=new Socket(InetAddress.getLocalHost(), 5000);
os=s.getOutputStream();
string="Hi there. Current time is "+(new Date());
os.write(string.getBytes());
os.flush();
//Thread.sleep(10000);
os.close();
s.close();
}
}
Code:
package alex.gw;
import java.net.*;
import java.io.*;
class Server
{
public static void main(String[] args) throws Exception {
ServerSocket ss;
Socket s;
InputStream is;
int charsRead;
BufferedReader br;
InputStreamReader isr;
String line;
byte[] byteArray;
byteArray=new byte[256];
System.out.println("Listening to 5000.");
ss=new ServerSocket(5000, 1, InetAddress.getLocalHost());
//System.out.println("Binding...");
//ss.bind(new InetSocketAddress("localhost", 5000));
while (true) {
System.out.println("Accepting new connections.");
s=ss.accept();
System.out.println("Trying to get a new input stream.");
is=s.getInputStream();
isr=new InputStreamReader(is);
br=new BufferedReader(isr);
while ((line=br.readLine())!=null) {
System.out.println(line);
}
br.close();
isr.close();
is.close();
s.close();
}
}
}
Fire up the server first. Then run the client.
To modify this sort of thing to keep the clients, you just simply store the Socket object you got in the server from a connecting client someplace. This part:
System.out.println("Accepting new connections.");
s=ss.accept();
You can modify it to something like this:
Vector<Socket> allClients;
...
System.out.println("Accepting new connections.");
s=ss.accept();
allClients.addElement(s);
Then give the Socket s to some other class to handle input and output.