Introduction to Computing Concepts Note Set 23 Networking IP: 192.168.0.123 Network IP: 97.99.88.77 IP: 111.222.121.99 ClientServer Model Data Transfer Between client and server ClientActively makes a Connection to the server ServerWaits Passively for a connection Each computer has many “ports” that allow it to communicate with More than one other computer. In Java - Server Let’s say this server is running on computer w/ IP 192.168.0.101 ServerSocket listener = new ServerSocket(3333); Socket connection; //Blocks and waits for someone to attempt to connect //Will accept the connection only on the port listed above connection = listener.accept(); //More code to come So a client on another computer would attempt to connect to IP 192.168.0.101 on port 3333. In Java - Client Let’s say this client is running on computer w/ IP 192.168.0.202 //attempt to connect to server running on Socket client = new Socket(“192.168.0.101”, 3333); Communication • Two computer connected to the same socket can send and receive information to/from each other //attempt to connect to server running on Socket client = new Socket(“192.168.0.101”, 3333); //Write to socket with a printwriter PrintWriter output = new PrintWriter(client.getOutputStream()); //Read from socket with a Scanner – just like from //the keyboard Scanner input = new Scanner (client.getInputStream()); Exception Handling • Helps recover from runtime errors ▫ Try to connect to a server but can’t get a connection • Some methods throw exceptions that must be caught in the code you write. try { //attempt to connect to server running on Socket client = new Socket(“192.168.0.101”, 3333); } catch (Exception e) { System.out.println(“Error”); System.out.println(e.getMessage()); } Breakout IN Groups • Modify Simple Server ▫ Have server generate a random number between 1 and 10, then wait for a connection ▫ Upon connection, read a number from the input stream and check. ▫ Send back to client a message of correct guess or incorrect guess • Modify Simple Client ▫ Get a number between 1 and 10 from the user ▫ Connect to server and then send number ▫ Read back response and display to the user