I have to build a server and a client in Java. The server opens a connection on port 18163. The client connects to the server and establishes a number X, the server sends the message "guess", the server received the message repeatedly attempts to determine the value of X to the client sending the message "I feel Y" where Y is the value of a integer. When the client receives the message "I feel Y" sends to the server: "Same" if the number is correct, "Not equal if the number is not correct." If the number is correct, the server sends the client the "Close" and the client closes the connection.
I have to implement this program without the use of thread! I tried that, but it doesn't work.
CLIENT:
public class Client{
public static void main(String[] args)throws Exception{
Socket c= new Socket("127.0.0.1",18163);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(c.getInputStream()));
DataOutputStream outToServer=new DataOutputStream(c.getOutputStream());
int min=1,max=10;
String frase;
int n1;
int numcasuale=(min+(int)(Math.random()*((max - min)+1)));
System.out.println("Num casuale generato: "+numcasuale);
do{
frase=inFromServer.readLine();
n1=Integer.parseInt(frase);
System.out.println("DAL SERVER: PROVO "+n1);
}while(!(n1==numcasuale));
outToServer.writeBytes("UGUALE\n");
frase=inFromServer.readLine();
if(frase.equals("CLOSE")){
System.out.println("Esecuzione terminata.");
c.close();
}
}
}
SERVER:
public class Server{
public static void main(String[] args)throws Exception{
ServerSocket ss = new ServerSocket(18163);
int min=1,max=10,numcasuale;
String dallclient;
while(true){
Socket c= ss.accept();
System.out.println("Client connesso: "+ c.getRemoteSocketAddress());
DataOutputStream alclient=new DataOutputStream(c.getOutputStream());
BufferedReader dalclient =new BufferedReader(new InputStreamReader(c.getInputStream()));
dallclient= dalclient.readLine();
System.out.println("DAL CLIENT :"+dallclient);
do{
numcasuale=(min+(int)(Math.random()*((max - min)+1)));
alclient.write(numcasuale);
dallclient= dalclient.readLine();
System.out.println("DAL CLIENT: "+dallclient);
}while(!(dallclient.equals("UGUALE")));
}alclient.writeBytes("CLOSE\n");
}
}
I think in the server part you are missing an \\n
at this line:
while( !(dallclient.equals("UGUALE")) );
since the client is sending "UGUALE\\n"
outToServer.writeBytes("UGUALE\n");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.