我有UDP服务器等待客户端的请求并发送响应给他们。为了检查客户端是否在线,我需要向他们发送消息。(检查一下)。
但是!在客户端的PC上,用户可以选择一些消息并将其发送到服务器,然后等待服务器的响应。如何做这样的事情 - 用户可以向服务器发送消息,但同时客户端可以从服务器接收消息 ?将客户端的readLine
放在一个线程中recieve
进入另一个人?
这是客户端的主循环(ds - DatagramSocket。客户端 - 我自己的类)
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();
}
}
}
答案 0 :(得分:3)
在C / C ++套接字中,您通常使用“select()”调用来处理文本发生的任何输入 - 键盘,文件或网络。
在Java套接字中,您可以考虑查看“nio”:
答案 1 :(得分:1)
是的,您需要将客户端的至少一部分放入另一个线程中。
首先将客户端输入循环放入一个单独的线程中。
Thread t_input = new Thread() {
public void run() {
BufferedReader br_in = new BufferedReader(new InputStreamReader(System.in));
String cmd = br_in.readLine();
while(cmd != null) {
if(cmd.equals("exit")) { //stop the user input
client_Shutdown();
break;
}
//handle other user input
cmd = br_in.readLine();
}
}
};
t_input.start();