Networking
Networking
Networking
C o r e j a v a v o l u m e 2: ch a pt er 4
Objectives 2
• Connecting to a server
• Implementing servers
• Socket communication
21 FTP server
23
192.168.10.253
Telnet server
1. A connection-oriented service
2. A connectionless service
Connection-Oriented Service 10
while (in.hasNextLine())
{
String line = in.nextLine();
System.out.println(line);
}
}//inner try
finally
{
s.close();
}
}//outer try
catch(IOException ex)
{
System.out.println("We have the following exception: "+ex);
}
}
}
Example3: SocketTest3 22
• For example,
InetAddress address =
InetAddress.getByName("www.kau.edu.sa");
will return an InetAddress object that encapsulates the
sequence of four bytes
• As: 192.162.72.233
Host Names and IP Addresses 27
• InetAddress[] addresses =
InetAddress.getAllByName("www.google.com");
The Loopback Address and localhost 28
• The command:
Socket incoming = server.accept();
41
Example4: EchoServer output using telnet
42
Example4: EchoServer output using telnet 43
Example5: EchoClient 44
public class EchoClient
{ public static void main(String[] args)
{
try(var client = new Socket("127.0.0.1", 8189);
var in = new Scanner(client.getInputStream(),
StandardCharsets.UTF_8);
PrintWriter out = new PrintWriter(client.getOutputStream(),
true, StandardCharsets.UTF_8);
){
String str;
str = in.nextLine();
System.out.println("Server says: " + str);
out.println("This is the client");
str = in.nextLine();
System.out.println("Server says: " + str);
out.println("BYE");
str = in.nextLine();
System.out.println("Server says: " + str);
}//end of try-with
catch(IOException e)
{
System.out.println("Exception in our client: " + e);
} } }
Example5: EchoClient output 45
• while (true)
{
t.start();
}
Servers and Multiple Clients 49
while (true)
{
Socket incoming = s.accept();
System.out.println("Spawning client: " + i);
Runnable r = new ThreadedEchoHandler(incoming);
var t = new Thread(r);
t.start();
i++;
}
}
catch (IOException e)
{
e.printStackTrace();
} } }
Example6: ThreadedServer page 2 52
class ThreadedEchoHandler implements Runnable
{
private Socket incoming;
public ThreadedEchoHandler(Socket incomingSocket)
{
incoming = incomingSocket;
}
public void run()
{
try (InputStream inStream = incoming.getInputStream();
OutputStream outStream = incoming.getOutputStream();
var in = new Scanner(inStream, StandardCharsets.UTF_8);
var out = new PrintWriter(outStream, true /* autoFlush */,
StandardCharsets.UTF_8);
){
out.println( "Hello! Enter BYE to exit." );
var done = false;
while (!done)
{
String line = in.nextLine();
out.println("Echo: " + line);
if (line.trim().equals("BYE"))
done = true;
} }
catch (IOException e)
{
e.printStackTrace();
} } }
Example6: ThreadedServer output
Server is running but there are no clients yet 53
Example6: ThreadedServer output 54
• out.writeDouble(Data2);
Object Network Streams 61
• out.writeObject(Obj2);
Socket Timeouts of reading from Socket 62
InputStream in = s.getInputStream();
{ // react to timeout
{… }
Socket Timeouts of connection establishment 65
• http://www.kau.edu.sa/page2
• Or
o setDoOutput
o setConnectTimeout
Using a URLConnection to Retrieve Information 76
• connection.getContentLength();
• connection.getContentEncoding();
getContentLength: 6173
getContentEncoding: null
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
</head>
• When the user clicks the Submit button, the text in the
text fields and the settings of any checkboxes, radio
buttons, and other input elements are sent back to the
web server. The web server invokes a program that
processes the user input
Posting form data 83
• POST
GET command 86
• as_filetype=extension
• Notice that the parameter list starts with a ‘?’ and the
individual parameters are separated with a ‘&’
Example8: HTTPGet page 1 91
import java.io.*;
import java.net.*;
import java.nio.charset.*;
import java.util.*;
public class HTTPGet
{ public static void main(String[] args)
{
try
{ String urlName =
"https://www.google.com/search?q=kau+university&as_eq=FCIT&as_filetype=pdf&num=2
";
var url = new URL(urlName);
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0;
Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74
Safari/537.36");
connection.connect();
try (var in = new Scanner(connection.getInputStream(),
StandardCharsets.UTF_8))
{ while(in.hasNextLine())
System.out.println(in.nextLine());
}
}
catch (IOException e)
{
e.printStackTrace();
} } }
Example8: HTTPGet explanation 92
• HTTP headers are the core part of the HTTP requests and
responses, and they carry information about the client,
the requested page, and the server
.uri(URI.create("https://www.google.com/search?q=kau+university&as_eq=FCIT&as_f
iletype=pdf&num=2"))
.setHeader("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5
Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Mobile
Safari/537.36")
.build();
.uri(URI.create("https://weather.visualcrossing.com/VisualCrossingWebServices/r
est/services/timeline/London?unitGroup=metric&include=days&key=5MGJ7ZFDHFN4GD4E
ASEPJYCDW&contentType=csv"))
.build();
• city=San Francisco
• state=CA
Example10: HTTPPost explanation 10
6
• We need to set the header field: content-
type