Share
Embed
CSC309 Lecture 16
Software Engineering II
More Tools II
(202405)
Javier Gonzalez-Sanchez PRO
February 15, 2023
Transcript
15 slides
-
jgs CSC 309 Software Engineering II Lecture 16: More Tools
II Dr. Javier Gonzalez-Sanchez [email protected] www.javiergs.com Building 14 -227 Office Hours: By appointment -
jgs Javier Gonzalez-Sanchez | CSC 309 | Winter 2023 |
3 import java.net.*; public class Server implements Runnable{ public void run() { final int PORT = 12345; try { ServerSocket serverSocket = new ServerSocket(PORT)); System.out.println("Server started. Waiting for a client..."); Socket clientSocket = serverSocket.accept(); System.out.println("Client connected: " + clientSocket); BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter( clientSocket.getOutputStream(), true); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("Client: " + inputLine); out.println("Server received: " + inputLine); } } catch (IOException e) { e.printStackTrace(); } } } Server Runnable -
jgs Javier Gonzalez-Sanchez | CSC 309 | Winter 2023 |
4 public class Client implements Runnable{ public void run() { final String SERVER_ADDRESS = "localhost"; final int PORT = 12345; try { Socket socket = new Socket(SERVER_ADDRESS, PORT); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream())); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Connected to server."); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("Server: " + in.readLine()); } } catch (UnknownHostException e) { System.err.println("Unknown host: " + SERVER_ADDRESS); System.exit(1); } catch (IOException e) { System.err.println("Error connecting to server"); e.printStackTrace(); System.exit(1); } } } Runnable Client -
jgs Javier Gonzalez-Sanchez | CSC 309 | Winter 2023 |
5 public static void main(String[] args) { Client server = new Server(port); Thread t1= new Thread(server); t1.start (); Client client = new Client(address, port); Thread t2= new Thread(client); t2.start (); } Multi-Threading -
jgs Javier Gonzalez-Sanchez | CSC 309 | Winter 2023 |
8 Pong 0 :: Timer, Socket, Listeners, UI -
jgs Javier Gonzalez-Sanchez | CSC 309 | Winter 2023 |
10 Pong 1 :: Timer, Socket, Listeners, UI -
jgs CSC 309 Software Engineering II Lab 14: Work in
your Sprint Dr. Javier Gonzalez-Sanchez [email protected] www.javiergs.com Building 14 -227 Office Hours: By appointment -
jgs Javier Gonzalez-Sanchez | CSC 309 | Winter 2023 |
14 Let’s Work -
jgs CSC 309 Software Engineering II Javier Gonzalez-Sanchez, Ph.D. [email protected]
Winter 2023 Copyright. These slides can only be used as study material for the class CSC308 at Cal Poly. They cannot be distributed or used for another purpose.