Lab 6: Introduction to Sockets (Web Programming – Part 1) Reference: Head First Java (2 nd...

6
Lab 6: Introduction to Sockets (Web Programming – Part 1) Reference: Head First Java (2 nd Edition) by Kathy Sierra & Bert Bates

Transcript of Lab 6: Introduction to Sockets (Web Programming – Part 1) Reference: Head First Java (2 nd...

Lab 6: Introduction to Sockets (Web Programming – Part 1)Reference: Head First Java (2nd Edition) by Kathy Sierra & Bert Bates

Connecting with the outside world• Your Java program can reach out and communicate with a

program on another machine.• All the low-level networking details are taken care of by

classes in the java.net library.

• One of Java’s big benefits is that sending and receiving data over a network is just I/O with a slightly different connection stream at the end of the chain.

• We are going to learn how to connect to the outside world by creating client and server sockets.

What is a Socket?• To connect to another machine, we need a Socket connection. A

Socket is an object that represents a network connection between two machines.

• A connection is a relationship between two machines, where two pieces of software know about each other and, most importantly, they know how to communicate with each other.

• To make a Socket connection, you need to know two things about the server first:1. Who it is (IP Address).2. Which port it’s running on

(Port number).

Getting the client to work1. Client connects to the server by establishing a Socket connection.

2. Client sends a message to the server.

3. Client gets a message from the server.

Reading from a Socket• To read data from a Socket, we use a BufferedReader.

1. Make a Socket connection to the Server.

Socket gameSocket = new Socket(IPaddress, PortNumber);

2. Make an InputStreamReader chained to the Socket’s low-level (connection) input stream.

InputStreamReader stream = new InputStreamReader(gameSocket.getInputStream());

3. Make the BufferedReader and read!BufferedReader = new BufferedReader(stream);

String message = reader.readLine();

Writing to a Socket• To write data to a Socket, we use a PrintWriter.

1. Make a Socket connection to the Server.

Socket gameSocket = new Socket(IPaddress, PortNumber);

2. Make a PrintWriter chained to the Socket’s low-level (connection) output stream.

PrintWriter writer = new PrintWriter(gameSocket.getInputStream());

3. Write (print) something!writer.println(“message to send”);