import java.io.*; import java.net.*; import java.util.*; class TCPServer { publi
ID: 3624174 • Letter: I
Question
import java.io.*;import java.net.*;
import java.util.*;
class TCPServer {
public static void main(String argv[]) throws Exception {
ServerSocket welcomeSocket = new ServerSocket(5555);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));//get client move
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
int ServerMove;
int square[9] = 0;
ClientMove = integer.parseInt(inFromClient); //take client sent move and convert to int
if(ClientMove > 0 || ClientMove < 10){
square[ClientMove]=2;//update server's version of array
}
do{
Random generator = new Random();
int ServerMove = generator.nextInt(10) + 1;//server makes a move
}while (square[ServerMove]==2);
square[ServerMove]=1;//updates its array
outToClient.writeBytes(ServerMove.toString()+ ' ');//send server's move
}
}
}
Explanation / Answer
Fixed all compile-time errors and played a game. Next time, I suggest you compile after each line.
import java.io.*;
import java.net.*;
import java.util.*;
public class TCPServer {
public static void main(String argv[]) throws Exception {
ServerSocket welcomeSocket = new ServerSocket(5555);
Socket connectionSocket = welcomeSocket.accept();
DataInputStream inFromClient = new DataInputStream(connectionSocket.getInputStream());//get client move
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
while(true) {
int ServerMove;
int[] square = new int[9];
int ClientMove = inFromClient.readInt(); //take client sent move and convert to int
if(ClientMove >= 0 || ClientMove < 9){
square[ClientMove]=2;//update server's version of array
}
do{
ServerMove = (int)Math.floor(Math.random()*9);
}while (square[ServerMove] != 0);
square[ServerMove]=1;//updates its array
outToClient.writeInt(ServerMove);//send server's move
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.