

























Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Prepare-se para as provas
Estude fácil! Tem muito documento disponível na Docsity
Prepare-se para as provas com trabalhos de outros alunos como você, aqui na Docsity
Encontra documentos específicos para os exames da tua universidade
Prepare-se com as videoaulas e exercícios resolvidos criados a partir da grade da sua Universidade
Responda perguntas de provas passadas e avalie sua preparação.
Ganhe pontos para baixar
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Redes, Networking
Tipologia: Resumos
1 / 33
Esta página não é visível na pré-visualização
Não perca as partes importantes!


























33-2 Chapter 33 Networking
33.1 Introduction
33.2 Client/Server Computing
33.2.1 Server Sockets
Point
Key
IP address
domain name domain name server
stream-based communication packet-based communication
Point
Key
socket
server socket port
33-4 Chapter 33 Networking
Note The Socket constructor throws a java.net.UnknownHostException if the host cannot be found.
33.2.3 Data Transmission through Sockets
UnknownHostException
int port = 8000; int port = 8000;
Connection Request
I/O Streams
Server Client
DataInputStream in; DataOutputStream out; ServerSocket server; Socket socket;
server = new ServerSocket(port); socket = server.accept(); in = new DataInputStream (socket.getInputStream()); out = new DataOutputStream (socket.getOutputStream()); System.out.println(in.readDouble()); out.writeDouble(aNumber);
String host = "localhost" DataInputStream in; DataOutputStream out; Socket socket;
socket = new Socket(host, port); in = new DataInputStream (socket.getInputStream()); out = new DataOutputStream (socket.getOutputStream());
System.out.println(in.readDouble());
out.writeDouble(aNumber);
InputStream input = socket.getInputStream(); OutputStream output = socket.getOutputStream();
DataInputStream input = new DataInputStream (socket.getInputStream()); DataOutputStream output = new DataOutputStream (socket.getOutputStream());
Tip Recall that binary I/O is more efficient than text I/O because text I/O requires encoding and decoding. Therefore, it is better to use binary I/O for transmitting data between a server and a client to improve performance.
33.2 Client/Server Computing 33-
compute area Server Client
radius
area
33.2.4 A Client/Server Example
Server radius
DataInputStream
socket.getInputStream
socket
Network
radius
DataOutputStream
socket.getOutputStream
socket
Client
(a)
Server area
DataOutputStream
socket.getOutputStream
socket
Network
area
DataInputStream
socket.getInputStream
socket
Client
(b)
Listing 33.1 Server.java
1 import java.io.; 2 import java.net.; 3 import java.util.Date;
33.2 Client/Server Computing 33-
Listing 33.2 Client.java
1 import java.io.; 2 import java.net.; 3 import javafx.application.Application; 4 import javafx.geometry.Insets; 5 import javafx.geometry.Pos; 6 import javafx.scene.Scene; 7 import javafx.scene.control.Label; 8 import javafx.scene.control.ScrollPane; 9 import javafx.scene.control.TextArea; 10 import javafx.scene.control.TextField; 11 import javafx.scene.layout.BorderPane; 12 import javafx.stage.Stage; 13 14 public class Client extends Application { 15 // IO streams 16 DataOutputStream toServer = null ; 17 DataInputStream fromServer = null ; 18 19 @Override // Override the start method in the Application class 20 public void start(Stage primaryStage) { 21 // Panel p to hold the label and text field 22 BorderPane paneForTextField = new BorderPane(); 23 paneForTextField.setPadding( new Insets( 5 , 5 , 5 , 5 )); 24 paneForTextField.setStyle( "-fx-border-color: green" ); 25 paneForTextField.setLeft( new Label( "Enter a radius: " )); 26 27 TextField tf = new TextField(); 28 tf.setAlignment(Pos.BOTTOM_RIGHT); 29 paneForTextField.setCenter(tf); 30 31 BorderPane mainPane = new BorderPane(); 32 // Text area to display contents 33 TextArea ta = new TextArea(); 34 mainPane.setCenter( new ScrollPane(ta)); 35 mainPane.setTop(paneForTextField); 36 37 // Create a scene and place it in the stage 38 Scene scene = new Scene(mainPane, 450 , 200 ); 39 primaryStage.setTitle( "Client" ); // Set the stage title 40 primaryStage.setScene(scene); // Place the scene in the stage 41 primaryStage.show(); // Display the stage 42 43 tf.setOnAction(e -> { 44 try { 45 // Get the radius from the text field 46 double radius = Double.parseDouble(tf.getText().trim()); 47 48 // Send the radius to the server 49 toServer.writeDouble(radius); 50 toServer.flush(); 51 52 // Get area from the server 53 double area = fromServer.readDouble(); 54 55 // Display to the text area 56 ta.appendText( "Radius is " + radius + "\n" ); 57 ta.appendText( "Area received from the server is " 58 + area + '\n' );
handle action event
read radius
write radius
read area
create UI
33-8 Chapter 33 Networking
60 catch (IOException ex) { 61 System.err.println(ex); 62 } 63 }); 64 65 try { 66 // Create a socket to connect to the server 67 Socket socket = new Socket( "localhost" , 8000 ); 68 // Socket socket = new Socket("130.254.204.36", 8000); 69 // Socket socket = new Socket("drake.Armstrong.edu", 8000); 70 71 // Create an input stream to receive data from the server 72 fromServer = new DataInputStream(socket.getInputStream()); 73 74 // Create an output stream to send data to the server 75 toServer = new DataOutputStream(socket.getOutputStream()); 76 } 77 catch (IOException ex) { 78 ta.appendText(ex.toString() + '\n' ); 79 } 80 } 81 }
ServerSocket serverSocket = new ServerSocket( 8000 );
Socket socket = serverSocket.accept();
Socket socket = new Socket( "localhost" , 8000 );
request connection
input from server
output to server
33-10 Chapter 33 Networking
System.out.println( "Client's IP Address is " + inetAddress.getHostAddress());
InetAddress address = InetAddress.getByName( "liang.armstrong.edu" );
Listing 33.3 IdentifyHostNameIP.java 1 import java.net.*; 2 3 public class IdentifyHostNameIP { 4 public static void main(String[] args) { 5 for ( int i = 0 ; i < args.length; i++) { 6 try { 7 InetAddress address = InetAddress.getByName(args[i]); 8 System.out.print( "Host name: " + address.getHostName() + " " ); 9 System.out.println( "IP address: " + address.getHostAddress()); 10 } 11 catch (UnknownHostException ex) { 12 System.err.println( "Unknown host or IP address " + args[i]); 13 } 14 } 15 } 16 }
33.3.1 How do you obtain an instance of InetAddress? 33.3.2 What methods can you use to get the IP address and hostname from an InetAddress?
33.4 Serving Multiple Clients
get an InetAddress get host name get host IP
Point
Check
Point
Key
33.4 Serving Multiple Clients 33-
while ( true ) { Socket socket = serverSocket.accept(); // Connect to a client Thread thread = new ThreadClass(socket); thread.start(); }
Server
Client 1... Client n
A server socket A socket for a on a port client A socket for a client
Listing 33.4 MultiThreadServer.java
1 import java.io.; 2 import java.net.; 3 import java.util.Date; 4 import javafx.application.Application; 5 import javafx.application.Platform; 6 import javafx.scene.Scene; 7 import javafx.scene.control.ScrollPane; 8 import javafx.scene.control.TextArea; 9 import javafx.stage.Stage; 10
33.5 Sending and Receiving Objects 33-
72 /** Run a thread */ 73 public void run() { 74 try { 75 // Create data input and output streams 76 DataInputStream inputFromClient = new DataInputStream( 77 socket.getInputStream()); 78 DataOutputStream outputToClient = new DataOutputStream( 79 socket.getOutputStream()); 80 81 // Continuously serve the client 82 while ( true ) { 83 // Receive radius from the client 84 double radius = inputFromClient.readDouble(); 85 86 // Compute area 87 double area = radius * radius * Math.PI; 88 89 // Send area back to the client 90 outputToClient.writeDouble(area); 91 92 Platform.runLater(() -> { 93 ta.appendText( "radius received from client: " + 94 radius + '\n' ); 95 ta.appendText( "Area found: " + area + '\n' ); 96 }); 97 } 98 } 99 catch (IOException ex) { 100 ex.printStackTrace(); 101 } 102 } 103 } 104 }
33.4.1 How do you make a server serve multiple clients?
33.5 Sending and Receiving Objects
update GUI
Point
Check
Point
Key
33-14 Chapter 33 Networking
Listing 33.5 StudentAddress.java
1 public class StudentAddress implements java.io.Serializable { 2 private String name; 3 private String street; 4 private String city; 5 private String state; 6 private String zip; 7 8 public StudentAddress(String name, String street, String city, 9 String state, String zip) { 10 this .name = name; 11 this .street = street; 12 this .city = city; 13 this .state = state; 14 this .zip = zip; 15 } 16 17 public String getName() { 18 return name; 19 } 20 21 public String getStreet() { 22 return street; 23 } 24 25 public String getCity() { 26 return city; 27 } 28 29 public String getState() { 30 return state; 31 } 32 33 public String getZip() { 34 return zip; 35 } 36 }
serialized
33-16 Chapter 33 Networking
38 HBox hBox = new HBox( 2 ); 39 pane.add(hBox, 1 , 2 ); 40 hBox.getChildren().addAll(tfCity, new Label( "State" ), tfState, 41 new Label( "Zip" ), tfZip); 42 pane.add(btRegister, 1 , 3 ); 43 GridPane.setHalignment(btRegister, HPos.RIGHT); 44 45 pane.setAlignment(Pos.CENTER); 46 tfName.setPrefColumnCount( 15 ); 47 tfStreet.setPrefColumnCount( 15 ); 48 tfCity.setPrefColumnCount( 10 ); 49 tfState.setPrefColumnCount( 2 ); 50 tfZip.setPrefColumnCount( 3 ); 51 52 btRegister.setOnAction( new ButtonListener()); 53 54 // Create a scene and place it in the stage 55 Scene scene = new Scene(pane, 450 , 200 ); 56 primaryStage.setTitle( "StudentClient" ); // Set the stage title 57 primaryStage.setScene(scene); // Place the scene in the stage 58 primaryStage.show(); // Display the stage 59 } 60 61 /** Handle button action */ 62 private class ButtonListener implements EventHandler
Listing 33.7 StudentServer.java
1 import java.io.; 2 import java.net.; 3 4 public class StudentServer {
register listener
server socket
output stream
send to server
33.5 Sending and Receiving Objects 33-
5 private ObjectOutputStream outputToFile; 6 private ObjectInputStream inputFromClient; 7 8 public static void main(String[] args) { 9 new StudentServer(); 10 } 11 12 public StudentServer() { 13 try { 14 // Create a server socket 15 ServerSocket serverSocket = new ServerSocket( 8000 ); 16 System.out.println( "Server started " ); 17 18 // Create an object output stream 19 outputToFile = new ObjectOutputStream( 20 new FileOutputStream( "student.dat" , true )); 21 22 while ( true ) { 23 // Listen for a new connection request 24 Socket socket = serverSocket.accept(); 25 26 // Create an input stream from the socket 27 inputFromClient = 28 new ObjectInputStream(socket.getInputStream()); 29 30 // Read from input 31 Object object = inputFromClient.readObject(); 32 33 // Write to the file 34 outputToFile.writeObject(object); 35 System.out.println( "A new student object is stored" ); 36 } 37 } 38 catch (ClassNotFoundException ex) { 39 ex.printStackTrace(); 40 } 41 catch (IOException ex) { 42 ex.printStackTrace(); 43 } 44 finally { 45 try { 46 inputFromClient.close(); 47 outputToFile.close(); 48 } 49 catch (Exception ex) { 50 ex.printStackTrace(); 51 } 52 } 53 } 54 }
server socket
output to file
connect to client
input stream
get from client
write to file
33.6 Case Study: Distributed Tic-Tac-Toe Games 33-
Listing 33.8 TicTacToeConstants.java
1 public interface TicTacToeConstants { 2 public static int PLAYER1 = 1 ; // Indicate player 1 3 public static int PLAYER2 = 2 ; // Indicate player 2 4 public static int PLAYER1_WON = 1 ; // Indicate player 1 won 5 public static int PLAYER2_WON = 2 ; // Indicate player 2 won 6 public static int DRAW = 3 ; // Indicate a draw 7 public static int CONTINUE = 4 ; // Indicate to continue 8 }
Listing 33.9 TicTacToeServer.java
1 import java.io.; 2 import java.net.;
Player 1
Server
Create a server socket.
Accept connection from the first player and notify the player who is Player 1 with token X.
Accept connection from the second player and notify the player who is Player 2 with token O. Start a thread for the session.
Player 2
Initialize user interface.
Request connection to the server and learn which token to use from the server.
Receive status from the server.
If WIN, display the winner. If Player 1 wins, receive Player 1's last move, and break the loop.
If DRAW, display game is over , and receive Player 1's last move, and break the loop.
If CONTINUE, receive Player 1's selected row and index and mark the cell for Player 1.
Wait for the player to move, and send the selected row and column to the server.
Handle a session:
Tell Player 1 to start.
Receive row and column of the selected cell from Player 1.
Determine the game status (WIN, DRAW, CONTINUE). If Player 1 wins, or draws, send the status (PLAYER1_WON, DRAW) to both players and send Player 1's move to Player 2. Exit.
If CONTINUE, notify Player 2 to take the turn, and send Player 1's newly selected row and column index to Player 2.
Receive row and column of the selected cell from Player 2.
If Player 2 wins, send the status (PLAYER2_WON) to both players, and send Player 2's move to Player 1. Exit.
If CONTINUE, send the status, and send Player 2's newly selected row and column index to Player 1.
33-20 Chapter 33 Networking
3 import java.util.Date; 4 import javafx.application.Application; 5 import javafx.application.Platform; 6 import javafx.scene.Scene; 7 import javafx.scene.control.ScrollPane; 8 import javafx.scene.control.TextArea; 9 import javafx.stage.Stage; 10 11 public class TicTacToeServer extends Application 12 implements TicTacToeConstants { 13 private int sessionNo = 1 ; // Number a session 14 15 @Override // Override the start method in the Application class 16 public void start(Stage primaryStage) { 17 TextArea taLog = new TextArea(); 18 19 // Create a scene and place it in the stage 20 Scene scene = new Scene( new ScrollPane(taLog), 450 , 200 ); 21 primaryStage.setTitle( "TicTacToeServer" ); // Set the stage title 22 primaryStage.setScene(scene); // Place the scene in the stage 23 primaryStage.show(); // Display the stage 24 25 new Thread( () -> { 26 try { 27 // Create a server socket
create UI
TicTacToeConstants
Runnable
TicTacToeServer
JApplet TicTacToeClient Cell
JFrame
Similar to Listing 18.
TicTacToeServer
+PLAYER1 = 1: int +PLAYER2 = 2: int +PLAYER1_WON = 1: int +PLAYER2_WON = 2: int +DRAW = 3: int +CONTINUE = 4: int
HandleASession TicTacToeClient
-player1: Socket -player2: Socket -cell: char[][] -continueToPlay: boolean
+run(): void -isWon(): boolean -isFull(): boolean -sendMove(out: DataOutputStream, row: int, column: int): void
-myTurn: boolean -myToken: char -otherToken: char -cell: Cell[][] -continueToPlay: boolean -rowSelected: int -columnSelected: int -fromServer: DataInputStream -toServer: DataOutputStream -waiting: boolean
+run(): void -connectToServer(): void -receiveMove(): void -sendMove(): void -receiveInfoFromServer(): void -waitForPlayerAction(): void
HandleASession
«interface» TicTacToeConstants
+main(args: String[]):void