我有 UDPserver 等待客户端的请求并发送响应给他们。为了检查客户是否在线,我需要向他们发送消息。(检查)。但是!在客户端的电脑上,用户可以选择一些消息并将其发送到服务器,然后等待服务器的响应。如何做这样的事情 -用户可以向服务器发送消息,但同时客户端可以从服务器接收消息?将客户端放入readLine
一个线程并recieve
放入另一个线程?
这是客户端的主循环(ds - DatagramSocket.Client - 我自己的类)
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();
}
}
主服务器的循环
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();
}
}
}