I’ve got UDPserver which waits for clients’ requests and the sends response to them. In order to chech whether clients are online or not I need to send message to them.(to check it).
But!On client’s pc user can choose some message and send it to server and then wait for response from server. How to make such a thing – user can send message to server but at the same time client can receive message from server?Put client’s readLine in one thread and recieve into another?
Here is the client’s main loop(ds – DatagramSocket. Client – my own class)
while(true){
try{
//variable client we use it in every condition
Client obj = null;
ds = null;
//REGR - registration FNDI - find ip FNDM - find mask GETL - get all CHKA - check all
System.out.println("PORT - ");
int port = Integer.parseInt(new BufferedReader(new InputStreamReader(System.in)).readLine());
ds = new DatagramSocket(port);
//wait for user's choice
System.out.println("Commands - REGR,FNDI,FNDM,GETL,CHKA");
String cmd = new BufferedReader(new InputStreamReader(System.in)).readLine();
if (cmd.equals("REGR"))
{
//sending data to server and waiting for its response
}
else if (cmd.equals("FNDI"))
{
//same
}
else if (cmd.equals("FNDM"))
{
//same
}
else if (cmd.equals("GETL"))
{
//same
}
else if(cmd.equals("CHKA"))//CHKA
{
//same
}
}catch(Exception exc)
{
System.out.println(exc);
return;
}
finally
{
if (ds!=null)
ds.close();
}
}
Main server’s loop
while(!stop){
myfile.write(aam.InputMsg.name());
System.out.println(aam.InputMsg);
DatagramPacket pack = new DatagramPacket(buf,buf.length);
socket.receive(pack);
//ports.add(pack.getPort());
//object from pack
Object o = Deserialize.Deserialization(buf);
//ok. first - REGR - so check on Client
if (o instanceof Client)//registration
{
//perform some task
}
else if (o instanceof InetAddress)//find client by IP
{
//same
}
else if (o instanceof String)//different messages - name to find, start test.
{
//same
}
else
{
throw new Exception("SOME WRONG DATA FROM CLIENT");
}
}
System.out.println("Server stopped");
}
catch(Exception exc)
{
System.out.println(exc);
}
finally{
if (socket!=null){
socket.close();
}
}
}
In C/C++ sockets, you’d typically use a “select()” call to process whatever input happens to occur text – keyboard, file or network.
In Java sockets, you might consider looking at “nio”:
http://tutorials.jenkov.com/java-nio/nio-vs-io.html