TCP/IP Programming

Download Report

Transcript TCP/IP Programming

TCP/IP Programming
Copyright (C) 2009 Dr.Yong Uk Song
Yonsei University Wonju Campus
What is TCP/IP?
 The Internet Protocol Suite (commonly known as TCP/IP) is the set
of communications protocols used for the Internet and other similar
networks.
 It is named from two of the most important protocols in it: the
Transmission Control Protocol (TCP) and the Internet Protocol (IP),
which were the first two networking protocols defined in this standard.
 The Internet Protocol Suite, like many protocol suites, may be viewed as
a set of layers. Each layer solves a set of problems involving the
transmission of data, and provides a well-defined service to the upper
layer protocols based on using services from some lower layers.
 The TCP/IP model consists of four layers. From lowest to highest, these
are the Link Layer, the Internet Layer, the Transport Layer, and the
Application Layer.
The Internet vs. an internet
 An internet
 A terminology in the field of data communication and
networking
 Full name: Internetwork
 Network of networks
 The Internet
 The Internet is a global system of interconnected computer
networks that use the standardized Internet Protocol Suite
(TCP/IP).
 A kind of internetwork
What is TCP/IP?
 The Internet Protocol Suite (commonly known as TCP/IP) is the set of
communications protocols used for the Internet and other similar
networks.
 It is named from two of the most important protocols in it: the
Transmission Control Protocol (TCP) and the Internet Protocol (IP),
which were the first two networking protocols defined in this standard.
 The Internet Protocol Suite, like many protocol suites, may be viewed as
a set of layers. Each layer solves a set of problems involving the
transmission of data, and provides a well-defined service to the upper
layer protocols based on using services from some lower layers.
 The TCP/IP model consists of four layers. From lowest to highest, these
are the Link Layer, the Internet Layer, the Transport Layer, and the
Application Layer.
Protocol
 A protocol is a set of rules which is used by computers to
communicate with each other across a network.
 A promise between network users or devices
What is TCP/IP?
 The Internet Protocol Suite (commonly known as TCP/IP) is the set of
communications protocols used for the Internet and other similar
networks.
 It is named from two of the most important protocols in it: the
Transmission Control Protocol (TCP) and the Internet Protocol
(IP), which were the first two networking protocols defined in this
standard.
 The Internet Protocol Suite, like many protocol suites, may be viewed as
a set of layers. Each layer solves a set of problems involving the
transmission of data, and provides a well-defined service to the upper
layer protocols based on using services from some lower layers.
 The TCP/IP model consists of four layers. From lowest to highest, these
are the Link Layer, the Internet Layer, the Transport Layer, and the
Application Layer.
TCP/IP & OSI 7 Layer
OSI 7 Layer
Application
Presentation
Session
Internet Protocol Suite
BGP · DHCP · DNS · FTP · GTP · HTTP · IMAP ·
IRC · Megaco · MGCP · NNTP · NTP · POP · RIP Application
· RPC · RTP · RTSP · SDP · SIP · SMTP · SNMP ·
SOAP · SSH · Telnet · TLS/SSL · XMPP · (more)
Transport
Network
TCP
ICMP
Transport
UDP
IP
ARP
RARP
Internet
Data Link
H/W interface: Ethernet, Token-Ring …
Physical
Link
What is TCP/IP?
 The Internet Protocol Suite (commonly known as TCP/IP) is the set of
communications protocols used for the Internet and other similar
networks.
 It is named from two of the most important protocols in it: the
Transmission Control Protocol (TCP) and the Internet Protocol (IP),
which were the first two networking protocols defined in this standard.
 The Internet Protocol Suite, like many protocol suites, may be viewed as
a set of layers. Each layer solves a set of problems involving the
transmission of data, and provides a well-defined service to the upper
layer protocols based on using services from some lower layers.
 The TCP/IP model consists of four layers. From lowest to highest, these
are the Link Layer, the Internet Layer, the Transport Layer, and
the Application Layer.
TCP/IP & OSI 7 Layer
OSI 7 Layer
Application
Presentation
Session
Internet Protocol Suite
BGP · DHCP · DNS · FTP · GTP · HTTP · IMAP ·
IRC · Megaco · MGCP · NNTP · NTP · POP · RIP Application
· RPC · RTP · RTSP · SDP · SIP · SMTP · SNMP ·
SOAP · SSH · Telnet · TLS/SSL · XMPP · (more)
Transport
Network
TCP
ICMP
Transport
UDP
IP
ARP
RARP
Internet
Data Link
H/W interface: Ethernet, Token-Ring …
Physical
Link
Why layers?
 Classification is a strategy to investigate and understand a
complicated phenomenon.
 Classification is used everywhere:
 Transportation
 Motor vehicle : Bus, Taxi, Truck, …
 Academy
 Machine learning : Supervised learning, Unsupervised learning
 …
 "Systems approach" or "Divide and Conquer" are another, but
more sophisticated, names of classification.
 It was necessary for network developers to understand the
network protocols by classifying the protocols, and they found that
the concept of layer is the best way to classify the protocols.
Tasks involved in sending a letter
The interaction between layers in the
OSI model
Internet sockets
 Internet sockets (in plural) are an application
programming interface (API) in an operating system,
used for inter-process communication.
 Internet sockets constitute a mechanism for delivering
incoming data packets to the appropriate application process,
based on a combination of local and remote IP addresses and
port numbers.
 Client-server model
 Computer processes that provide application services are called
servers, and create sockets on start up that are in listening state.
 These sockets are waiting for initiatives from client programs.
Application Programming Interface
 An application programming interface (API) is a set of
routines, data structures, object classes and/or protocols
provided by libraries and/or operating system services in
order to support the building of applications.
 A set of commands
Internet sockets
 Internet sockets (in plural) are an application programming
interface (API) in an operating system, used for inter-process
communication.
 Internet sockets constitute a mechanism for delivering
incoming data packets to the appropriate application process,
based on a combination of local and remote IP addresses
and port numbers.
 Client-server model
 Computer processes that provide application services are called
servers, and create sockets on start up that are in listening state.
 These sockets are waiting for initiatives from client programs.
IP Address
 An Internet Protocol (IP) address is a numerical
identification and logical address that is assigned to devices
participating in a computer network utilizing the Internet
Protocol for communication between its nodes.
 Although IP addresses are stored as binary numbers, they are
usually displayed in human-readable notations, such as
208.77.188.166 (for IPv4), and 2001:db8:0:1234:0:567:1:1
(for IPv6).
 Address of a computer or a device
Port Number
 A port is an application-specific or process-specific software
construct serving as a communications endpoint used by Transport
Layer protocols of the Internet Protocol Suite such as Transmission
Control Protocol (TCP) and User Datagram Protocol (UDP).
 A specific port is identified by its number, commonly known as
the port number, the IP address it is associated with, and the
protocol used for communication.
 ID of a server
 Default port numbers
 Web server : 80
 FTP server : 21
 IP address : Port number  Building address : Room number
Socket Programming in Java
 Internet sockets constitute a mechanism for delivering
incoming data packets to the appropriate application process.
 Internet sockets support only the lower three layers of the
Internet Protocol Suite: the Link Layer, the Internet Layer,
and the Transport Layer.
 Internet sockets have only sending and receiving commands.
 To send: getOutputStream( )
 To receive: getInputStream( )
 Other commands are for initialization and finalization.
 To initialize: ServerSocket, accept, Socket
 To finalize: close( )
Socket Programming in Java
Server
Package
Class &
Methods
Client
import java.io.*;
import java.net.*;
import java.io.*;
import java.net.*;
ServerSocket(int port)
Socket accept( );
InputStream
getInputStream( );
OutputStream
getOutputStream( );
void close( );
Socket(String host, int port)
InputStream getInputStream( );
OutputStream
getOutputStream( );
void close( );
UnknownHostException
Exceptions
Socket Programming in Java : Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(clientConn.getInputStream()));
String request = input.readLine();
System.out.println(request);
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
Socket Programming in Java
Server
Package
Class &
Methods
Client
import java.io.*;
import java.net.*;
import java.io.*;
import java.net.*;
ServerSocket(int port)
Socket accept( );
InputStream
getInputStream( );
OutputStream
getOutputStream( );
void close( );
Socket(String host, int port)
InputStream getInputStream( );
OutputStream
getOutputStream( );
void close( );
UnknownHostException
Exceptions
Socket Programming in Java : Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
PrintWriter output = new
PrintWriter(socket.getOutputStream(), true);
output.println("Hello, from client");
output.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
Scenario 1:
Client Sends and Server Receives
TCP/IP (1) : Client TCPIP1Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
PrintWriter output = new
PrintWriter(socket.getOutputStream(), true);
output.println("Hello, from client");
output.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
TCP/IP (1) : Server TCPIP1Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(clientConn.getInputStream()));
String request = input.readLine();
System.out.println(request);
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
Digression on Java
 Variable
 A named identifier to store a value
 The "request" is a variable.
 Type
 Type of a value
 String, int, double, …
 The type of the variable "request" is a String, which means that
the type of value stored in "request" is a String.
TCP/IP (1)
 Exercise
 Make client and server programs such that:
 The client sends a string "Hello, I am Alice.".
 The server receives the string and prints it out.
 Project names
 Client - TCPIP1X1Client
 Server - TCPIP1X1Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of
server to each student respectively. After testing, switch the roles and
do the same things again.
 Something wrong?
 Try to use the debugger.
Scenario 2:
Server Sends and Client Receives
TCP/IP (2) : Server TCPIP2Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
PrintWriter output = new PrintWriter(clientConn.
getOutputStream(), true);
output.println("Hello, from server");
output.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
TCP/IP (2) : Client TCPIP2Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String response = input.readLine();
System.out.println(response);
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
TCP/IP (2)
 Exercise
 Make client and server programs such that:
 The server sends a string "Hello, I am Bob.".
 The client receives the string and prints it out.
 Project names
 Client - TCPIP2X1Client
 Server - TCPIP2X1Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of
server to each student respectively. After testing, switch the roles and
do the same things again.
 Something wrong?
 Try to use the debugger.
Not Any More Except Sockets?
Not Any More Except Sockets?
 The TCP/IP model consists of four layers: the Link Layer, the
Internet Layer, the Transport Layer, and the Application
Layer.
 On the other hand, Internet sockets support delivery of data
from a sender to a receive, which means that Internet sockets
supports only the lower three layers: the Link Layer, the
Internet Layer, and the Transport Layer.
 It seems that the TCP/IP (1) and TCP/IP (2) work well with
only the Internet sockets.
 Does that mean we do not need any more except Internet
sockets in Internet programming?
Not Any More Except Sockets?
 We need more promises (i.e.
protocols) about dialogue and data
presentation.
 Dialogue
 Who starts first?
 How many iterations?
 …
 Data Presentation
 Binary or ASCII, and additional
format?
 How designates the end of
message?
 …
 The TCP/IP (1) and TCP/IP (2)
work with not only Internet sockets
but also application layer protocols.
 TCP/IP (1)
 Dialogue
 Client first
 Server says nothing
 Only one iteration
 Presentation
 ASCII, text
 [Enter] designate the end of message
 [Enter] is an EOLN (End of Line)
character.
 TCP/IP (2)
 Dialogue
 Server first
 Client says nothing
 Only one iteration
 Presentation
 ASCII, text
 [Enter] designate the end of message
Not Any More Except Sockets?
 Exercise
 Make client and server programs such that:
 The client sends a string "Hello, I am Alice.\nHow are you doing?".
 The server receives the string and prints it out.
 Project names
 Client - TCPIPNX1Client
 Server - TCPIPNX1Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to
each student respectively. After testing, switch the roles and do the same things
again.
 Something wrong?
 Try to use the debugger.
 What is the problem?
 Presentation
Not Any More Except Sockets?
 Exercise
 Make client and server programs such that:
 The client receives a string and prints it out.
 The server receives a string and prints it out.
 Project names
 Client - TCPIPNX2Client
 Server - TCPIPNX2Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to
each student respectively. After testing, switch the roles and do the same things
again.
 Something wrong?
 Try to use the debugger.
 What is the problem?
 Dialogue
Not Any More Except Sockets?
 Exercise
 Make client and server programs such that:
 The client sends a string "Hello, I am Alice.".
 The server sends a string "Hello, I am Bob.".
 Project names
 Client - TCPIPNX3Client
 Server - TCPIPNX3Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to
each student respectively. After testing, switch the roles and do the same things
again.
 Something wrong?
 Try to use the debugger.
 What is the problem?
 Dialogue
Notes on Protocols
 Protocols must be defined exactly considering all possible
situations.
 Moreover, the defined protocols must be exactly
implemented in client and server programs.
Scenario 3:
Client Requests
and Server Responds
TCP/IP (3) : Client TCPIP3Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(),
true);
output.println("Request from client");
String response = input.readLine();
System.out.println(response);
output.close();
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
TCP/IP (3) : Server TCPIP3Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
String request = input.readLine();
System.out.println(request);
output.println("Response from server");
output.close();
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
TCP/IP (3)
 Exercise
 Make client and server programs such that:
 The client sends a string "What is your name?".
 The server receives the string, prints it out, and then sends a string "I am Alice.".
 The client receives the string, and prints it out.
 Project names
 Client - TCPIP3X1Client
 Server - TCPIP3X1Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to
each student respectively. After testing, switch the roles and do the same
things again.
 Something wrong?
 Try to use the debugger.
Scenario 4:
Server Requests
and Client Responds
TCPIP (4) : Server TCPIP4Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
output.println("Request from server");
String request = input.readLine();
System.out.println(request);
output.close();
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
TCPIP (4) : Client TCPIP4Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(),
true);
String response = input.readLine();
System.out.println(response);
output.println("Response from client");
output.close();
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
TCP/IP (4)
 Exercise
 Make client and server programs such that:
 The server sends a string "What is your name?".
 The client receives the string, prints it out, and then sends a string "I am Bob.".
 The server receives the string, and prints it out.
 Project names
 Client - TCPIP4X1Client
 Server - TCPIP4X1Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to
each student respectively. After testing, switch the roles and do the same
things again.
 Something wrong?
 Try to use the debugger.
Digression
if statement
if statement
 A control statement for
division
 Syntax
if (expression) {
statement(s)1
} else {
statement(s)2
}
 Control and execution
 If evaluation result of the
"expression" is true, then
"statement(s)1" is executed.
 Otherwise, "statement(s)2" is
executed.
 e.g.
if (n > 0) {
a = 1;
} else {
a = 0;
}
 Controls in programming
 Sequence
 Division
 Repetition
if statement Java1
 Example
String response = "I love you.";
if (response.contains("love")) {
System.out.println(response);
System.out.println("Comment: You are lucky.");
} else {
System.out.println(response);
}
 In an object-oriented programming language like Java, we can
apply a command like "contains" to a String variable like
"response".
 Almost commands in Java return some values; "contains" returns
"true" or "false".
if statement
 Exercise
 Make a Java program such that:
 Set a string variable response as "I am fine.".
 Print out the value of the response
 If the response contains a string "fine", then add a comment "Comment:
Good!".
 Project name
 Java1X1
Scenario 5:
Server's Behavior Depends on Request
TCPIP (5) : Client TCPIP5Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(),
true);
output.println("I love you.");
String response = input.readLine();
System.out.println(response);
output.close();
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
TCPIP (5) : Server TCPIP5Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
String request = input.readLine();
System.out.println(request);
if (request.contains("love")) {
System.out.println("Comment: You are lucky.");
}
output.println("Thank you.");
output.close();
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
TCP/IP (5)
 Exercise
 Make client and server programs such that:
 The client sends a string "I am fine.".
 The server receives the string, prints it out, and then sends a string "Thank you.". If the
message from the client contains a string "fine", the server prints out a comment
"Comment: Good!", too.
 The client receives the string, and prints it out.
 Project names
 Client - TCPIP5X1Client
 Server - TCPIP5X1Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to
each student respectively. After testing, switch the roles and do the same things
again.
 Something wrong?
 Try to use the debugger.
Digression
Standard I/O
Standard I/O
 Standard I/O
 Standard Input and Output
 Standard Output
 To print out on its monitor
 Standard Input
 To read from its keyboard
Standard I/O
 Syntax
 void System.out.print(Object)
 void System.out.println(Object)
 e.g.
System.out.print("String");
System.out.print(123);
System.out.println("String");
System.out.println(123);
 The command "print" does not print out an EOLN(i.e.
[Enter]) character.
Standard I/O
 Exercise
 Make a Java program such that:
 Print out like below:
Line 1
Line 2
Line 3
 Use the "println" command.
 What if using "print" instead of "println"?
 Project name
 Java2X1
Standard I/O
 Syntax
 BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
 String BufferedReader.readLine( ) throws IOException
 e.g.
import java.io.*;
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String str = reader.readLine();
System.out.print("You typed - ");
System.out.println(str);
} catch (Exception e) {
System.err.println(e);
}
Standard I/O
 Exercise
 Make a Java program such that:
 Input a string and print out the string.
 Project name
 Java2X2
Standard I/O
 Exercise
 Make a Java program such that:
 Input a string.
 If the string contains "love", then print out "Me, too.".
 Otherwise, just print out the input string.
 Project name
 Java2X3
Scenario 6:
Two Users using Client and Server Send
and Receive Messages
TCPIP (6) : Client TCPIP6Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
System.out.print("Input> ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String request = reader.readLine();
output.println(request);
String response = input.readLine();
System.out.println("Server> " + response);
output.close();
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
TCPIP (6) : Server TCPIP6Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
String request = input.readLine();
System.out.println("Client> " + request);
if (request.contains("love")) {
System.out.println("Comment:You are lucky.");
}
System.out.print("Input> ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String response = reader.readLine();
output.println(response);
output.close();
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
TCP/IP (6)
 Exercise
 Make client and server programs such that:
 The client inputs a string from its user, and sends the input string to the server.
 The server receives the string, prints it out. If the message from the client contains a string
"fine", the server prints out a comment "Comment: Good!", too.
 The server inputs a string from its user, and sends the input string to the client.
 The client receives the string, and prints it out.
 Project names
 Client - TCPIP6X1Client
 Server - TCPIP6X1Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to
each student respectively. After testing, switch the roles and do the same things
again.
 Something wrong?
 Try to use the debugger.
Quiz 2: TCP/IP Dialogue
Quiz 2 "TCP/IP Dialogue"

Develop and present a Java program which supports the dialogue between two persons using the
Internet sockets.
 The focus of this quiz is not only the technology but also the business. Try to make your program be
"cool" in terms of a business model; making more people use it, making more chance for
advertisement, …. Try to make as many idea as possible to make money from it.
 It is required for students to analyze the existing messenger services before programming.
 If students could not implement the additional "cool" functionality, it is fine. And just explain their
own "cool" functionality during the presentation.
 Evaluation is based on both of the presentation and the program.

Note:
 Due date: 07/08/2009
 This quiz is a group project.
 Each group of students should bring a PPT file and a program (including server and client) developed
by each group in a memory device on the due date, and present the PPT file first and then run the
program during the class.
 Bring only the folders and files under "src" folders for the program. Students would create a new
NetBeans project for the program during the class.
 Instructor will evaluate both of the presentation and the running result.
 Instructor’s computer will be used as a server or a client of the program. One student should run one
of the server or client on her/his computer, and the other student should run the other program on
instructor’s computer.
Evaluating Quiz 2
 Present your PPT file.
 Run NetBeans IDE on student’s computer and instructor’s




computer.
Create two new NetBeans projects on both of the computers.
Project names are determined by students.
Overwrite the src folders in your memory device onto the
src folders of the newly created project folders.
Run the server and the client and explain the functionality to
instructor.
Digression
for statement
for statement
 A control statement for repetition
 Syntax
for (expression1; expression2;
expression3) {
statement(s)
}
 Control and execution
 The "expression1" is evaluated.
 If evaluation result of the
"expression2" is true, then
"statement(s)" is executed.
 After the execution, the
"expression3" is evaluated.
 Go to the evaluation of the
"expression2".
 Otherwise, the whole "for"
statement is finished.
 e.g.
for (i = 0; i < 100; i++)
{
System.out.println(i);
}
 Controls in programming
 Sequence
 Division
 Repetition
for statement Java3
 Example
import java.io.*;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int i;
String response = "";
for (i = 0; response.contains("Quit") == false; i++) {
System.out.print("Input> ");
response = reader.readLine();
System.out.println(i + ": " + response);
}
} catch (Exception e) {
System.err.println(e);
}
 Note: "contains" returns "true" or "false".
for statement
 Exercise
 Make a Java program such that:
 Input a string from user and print it out as in Java3.
 If the string contains "Quit", then stop.
 If the string contains a string "fine", then add a comment "Comment:
Good!".
 Project name
 Java3X1
Scenario 7:
Two Users using Client and Server Talk to
Each Other
TCPIP (7) : Client TCPIP7Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String request = "", response = "";
for (; response.equals("Q") == false;) {
System.out.print("Input> ");
request = reader.readLine();
output.println(request);
response = input.readLine();
System.out.println("Server> " + response);
}
output.close();
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
TCPIP (7) : Server TCPIP7Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String request = "", response = "";
for (; response.equals("Q") == false;) {
request = input.readLine();
System.out.println("Client> " + request);
if (request.contains("love")) {
System.out.println("Comment:You are lucky.");
}
System.out.print("Input> ");
response = reader.readLine();
output.println(response);
}
output.close();
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
TCP/IP (7)
 Exercise
 Make client and server programs such that:
 Repeat the following until the server user inputs "Q":
 The client inputs a string from its user, and sends the input string to the server.
 The server receives the string, prints it out. If the message from the client contains a string "fine",
the server prints out a comment "Comment: Good!", too.
 The server inputs a string from its user, and sends the input string to the client.
 The client receives the string, and prints it out.
 Project names
 Client - TCPIP7X1Client
 Server - TCPIP7X1Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to each student
respectively. After testing, switch the roles and do the same things again.
 Something wrong?
 Try to use the debugger.
Multi-threading
Multi-threading
 Multi-threading is "programming with multiple threads".
 A thread of execution results from a fork of a computer
program into two or more concurrently running tasks.
 Multiple threads can exist within the same process and share
resources such as memory.
 Multiple threads:
 Multiple copies of a same program, which are running
simultaneously and share resources such as variables.
Multi-threading in Java (1)
 Declare a class which:
 Implements "Runnable"
 Has a method "public void run()"
 Create an object of the above class.
 Create an object of the class Thread.
 Execute the "start" method.
Multi-threading in Java (2)
 Declare a class.
 e.g.
public class MyThread implements Runnable
{
…
public void run()
{
…
}
…
}
Multi-threading in Java (3)
 Create an object of the above class.
 e.g.
MyThread myThread = new MyThread(…);
 Create an object of the class Thread.
 e.g.
Thread m_thread = new Thread(myThread);
 Execute the "start" method.
 e.g.
m_thread.start( );
Multi-threading in Java (4)
 Exercise
 Make a Java program such that:
 Create a thread, which prints out numbers from 1 through 10,000.
 On the other hand, the main method inputs a message from the standard
input, and prints it out.
 Project name
 Java4X1
Multi-threading in Java (4.1)
MAIN
THREAD
Create a thread
Input and print out a string
Print out numbers
from
1
through
10,000
Multi-threading in Java (4.2)
Java4X1.Main
import java.io.*;
MyThread myThread = new MyThread();
Thread m_thread = new Thread(myThread);
m_thread.start();
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String str = reader.readLine();
System.out.print("You typed - ");
System.out.println(str);
} catch (Exception e) {
System.err.println(e);
}
Multi-threading in Java (4.3)
Java4X1.MyThread
public class MyThread implements Runnable {
public void run() {
int i;
for (i = 0; i <= 10000; i++) {
System.out.println(i);
}
}
}
Digression: Thread.sleep Method
 Syntax
public static void sleep(long
milliseconds) throws
InterruptedException
 Causes the currently
executing thread to sleep
(temporarily cease
execution) for the specified
number of milliseconds,
subject to the precision and
accuracy of system timers
and schedulers.
 e.g.
try {
...
Thread.sleep(500);
...
} catch (Exception e) {
System.err.println(e);
}
Multi-threading in Java (5)
 Exercise
 Change Java4X1 such that:
 Create a thread, which prints out the numbers from 1 through 20 and
take a sleep for 500 milliseconds at each iteration.
 On the other hand, the main method inputs a message from the standard
input, and prints it out.
 Project name
 Java4X1 (unchanged from the previous exercise)
Multi-threading in Java (6)
 Exercise
 Make a Java program such that:
 Create a thread, which prints out the numbers from 1 through 20 and
take a sleep for 500 milliseconds at each iteration.
 On the other hand, the main method inputs a message from the standard
input, and then send the message to the thread.
 After printing out all the numbers, the thread prints out the message
from the main method.
 Project name
 Java4X2
Multi-threading in Java (6.1)
MAIN
THREAD
Create a thread
Input a string
Send the message to the thread
Print out numbers
from
1
through
20 while sleeping for 500 ms. at each
iteration
Print out the message from the main method
Multi-threading in Java (6.2)
Java4X2.Main
import java.io.*;
MyThread myThread = new MyThread();
Thread m_thread = new Thread(myThread);
m_thread.start();
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String str = reader.readLine();
myThread.m_msg = str;
} catch (Exception e) {
System.err.println(e);
}
Multi-threading in Java (6.3)
Java4X2.MyThread
public class MyThread implements Runnable {
public String m_msg;
MyThread() {
m_msg = "No";
}
public void run() {
int i;
try {
for (i = 0; i <= 20; i++) {
System.out.println(i);
Thread.sleep(500);
}
} catch (Exception e) {
System.err.println(e);
}
System.out.println("You typed in main: " + m_msg);
}
}
Multi-threading in Java (7)
 Exercise
 Make a Java program such that:
 Create a thread, which prints out the numbers from 1 through 20 and
take a sleep for 500 milliseconds at each iteration.
 On the other hand, the main method inputs a message from the standard
input, and waits until the thread stops.
 After printing out all the numbers, the thread sends a message that it will
stop immediately, and then stops.
 After receiving the message of stop, the main method stops.
 Project name
 Java4X3
Multi-threading in Java (7.1)
MAIN
THREAD
Create a thread
Input a string
Wait
Print out numbers
from
until
1
the
through
thread
20 while sleeping for 500 ms. at each
iteration
stops
Send a message that it will stop immediately
Stop
Multi-threading in Java (7.2) Java4X3.Main
import java.io.*;
MyThread myThread = new MyThread();
Thread m_thread = new Thread(myThread);
m_thread.start();
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String str = reader.readLine();
for (; myThread.m_bStopped == false;) {
System.out.println("Main: Waiting completion of Thread");
Thread.sleep(500);
}
System.out.println("Main: Thread stopped.");
System.out.println("Main: Typed in main - " + str);
System.out.println("Main: Finishing.");
} catch (Exception e) {
System.err.println(e);
}
Multi-threading in Java (7.3)
Java4X3.MyThread
public class MyThread implements Runnable {
public boolean m_bStopped;
MyThread() {
m_bStopped = false;
}
}
public void run() {
int i;
try {
for (i = 0; i <= 20; i++) {
System.out.println(i);
Thread.sleep(500);
}
} catch (Exception e) {
System.err.println(e);
}
System.out.println("Thread: Finishing.");
m_bStopped = true;
}
Multi-threading in Java (8)
 Exercise
 Make a Java program such that:
 Create a thread, which prints out the numbers from 1 through 20 and
take a sleep for 500 milliseconds at each iteration.
 On the other hand, the main method inputs a message from the standard
input, and then send the message to the thread.
 After sending the message, the main waits until the thread stops.
 After printing out all the numbers, the thread prints out the message
from the main method.
 After printing out the message, the thread sends a message that it will
stop immediately.
 Project name
 Java4X4
Multi-threading in Java (8.1)
MAIN
THREAD
Create a thread
Input a string
Print out numbers
Send the message to the thread
from
Wait
1
until
through
the
20 while sleeping for 500 ms. at each
iteration
thread
Print out the message from the main method
stops
Send a message that it will stop immediately
Stop
Multi-threading in Java (8.2)
Java4X4.Main
import java.io.*;
MyThread myThread = new MyThread();
Thread m_thread = new Thread(myThread);
m_thread.start();
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String str = reader.readLine();
myThread.m_msg = str;
for (; myThread.m_bStopped == false;) {
System.out.println("Main: Waiting completion of Thread");
Thread.sleep(500);
}
System.out.println("Main: Thread stopped.");
System.out.println("Main: Finishing.");
} catch (Exception e) {
System.err.println(e);
}
Multi-threading in Java (8.3)
Java4X4.MyThread
public class MyThread implements Runnable {
public String m_msg;
public boolean m_bStopped;
MyThread() {
m_msg = "No";
m_bStopped = false;
}
}
public void run() {
int i;
try {
for (i = 0; i <= 20; i++) {
System.out.println(i);
Thread.sleep(500);
}
} catch (Exception e) {
System.err.println(e);
}
System.out.println("Thread: Typed in main - " + m_msg);
System.out.println("Thread: Finishing.");
m_bStopped = true;
}
Multi-threading in Java (9)
 Exercise
 Make a Java program such that:
 Create a thread, which prints out repeatedly the last string sent from the
main method.
 The main method inputs strings from the standard input and sends the
strings to the thread repeatedly.
 If the last input string is "Q", the thread and the main method stops.
 Project name
 Java4X5
Demo:
A Messenger using Multi-threading
Demo (1)
 Project names
 Client - TCPIPD1Client
 Server - TCPIPD1Server
 Testing Scenarios
 Make a group of two students and assign a role of client and that
of server to each student respectively. After testing, switch the
roles and do the same things again.
Demo (2)
Server
Server
Main
(8888)
Client
Thread
Client
Client
Main
Server
Thread
(8889)
• Port numbers of main’s server and client thread’s server are
not required to be different. However, if the server and the client
are running on a same computer, the port numbers must be
different to each other.
Demo (3)
Server
MAIN
Client
THREAD
Create a server socket
MAIN
THREAD
Create a thread
Create a client socket
Listen and wait
Create a server socket
(#Port : +1)
Connect to server
Create a thread
Create a client socket
(#Port : +1)
Connect to client’s
server
Listen and wait
Receive a message and
print it out
Input a message from
user and send it
If the message is blank,
send a stop message to
the thread
If a stop message is
If the message is blank,
received from the main, send a stop message to
stop
the thread
Stop
Input a message from
user and send it
Stop
Receive a message and
print it out
If a stop message is
received from the main,
stop
Demo (4)
 Is the demo software perfect?
 Some problems in finish control
 GUI
 Others?
Application 1:
Automatic Map Service
Application 1

Exercise
 Make client and server programs such that:
 Repeat the following until the server user inputs "Q":
 The client inputs a string from its user, and sends the input string to the server.
 The server receives the string, prints it out.
o If the message from the client contains a string "Miami", the server replaces the string as "<A
HREF=\"http://maps.google.com/maps?q=Miami+of+Ohio+University\">Miami</A>".
o If the message from the client contains a string "Oxford", the server replaces the string as "<A
HREF=\"http://maps.google.com/maps?q=Oxford,+OH\">Oxford</A>".
 The server inputs a string from its user, and sends the input string to the client.
 The client receives the string, and prints it out.
 Project names
 Client - TCPIPA1Client
 Server - TCPIPA1Server

Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to each student respectively.
After testing, switch the roles and do the same things again.

Something wrong?
 Try to use the debugger.
Application 1 : Client TCPIPA1Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String request = "", response = "";
for (; response.equals("Q") == false;) {
System.out.print("Input> ");
request = reader.readLine();
output.println(request);
response = input.readLine();
if (response.contains("Miami")) {
response = response.replaceFirst("Miami", "<A
HREF=\"http://maps.google.com/maps?q=Miami+of+Ohio+University\">Miami</A>");
}
if (response.contains("Oxford")) {
response = response.replaceFirst("Oxford", "<A
HREF=\"http://maps.google.com/maps?q=Oxford,+OH\">Oxford</A>");
}
System.out.println("Server> " + response);
}
output.close();
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
Application 1 : Server TCPIPA1Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String request = "", response = "";
for (; response.equals("Q") == false;) {
request = input.readLine();
if (request.contains("Miami")) {
request = request.replaceFirst("Miami", "<A
HREF=\"http://maps.google.com/maps?q=Miami+of+Ohio+University\">Miami</A>");
}
if (request.contains("Oxford")) {
request = request.replaceFirst("Oxford", "<A HREF=\"http://maps.google.com/maps?q=Oxford,+OH\">Oxford</A>");
}
System.out.println("Client> " + request);
System.out.print("Input> ");
response = reader.readLine();
output.println(response);
}
output.close();
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
Application 1
 Is the software perfect in terms of map service?
 A large location database is required.
 It may slow down the software.
 Context problem
 Miami
 Miami of Ohio University?
 Miami, Florida?
 Oxford
 Oxford, Ohio?
 Oxford, England?
 Natural language processing
NateOn: Map Application
Application 2:
Alerting on a Financial Fraud
Application 2
 Exercise
 Make client and server programs such that:
 Repeat the following until the server user inputs "Q":
 The client inputs a string from its user, and sends the input string to the server.
 The server receives the string, prints it out.
o If the message from the client contains a string "$", "dollar", "buck", the server adds a comment
which reads "Alert: Some people assume your friend’s name. Be sure to confirm their identity."
 The server inputs a string from its user, and sends the input string to the client.
 The client receives the string, and prints it out.
 Project names
 Client - TCPIPA2Client
 Server - TCPIPA2Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to each student
respectively. After testing, switch the roles and do the same things again.
 Something wrong?
 Try to use the debugger.
Application 2 : Client TCPIPA2Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String request = "", response = "";
for (; response.equals("Q") == false;) {
System.out.print("Input> ");
request = reader.readLine();
output.println(request);
response = input.readLine();
System.out.println("Server> " + response);
if (response.contains("$") || response.contains("dollar") || response.contains("buck")) {
System.out.println("Alert: Some people assume your friend’s name. Be sure to confirm their
identity.");
}
}
output.close();
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
Application 2 : Server TCPIPA2Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String request = "", response = "";
for (; response.equals("Q") == false;) {
request = input.readLine();
System.out.println("Client> " + request);
if (request.contains("$") || request.contains("dollar") || request.contains("buck")) {
System.out.println("Alert: Some people assume your friend’s name. Be sure to confirm their identity.");
}
System.out.print("Input> ");
response = reader.readLine();
output.println(response);
}
output.close();
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
Application 2
 Is the software perfect in terms of alert service?
 Context problem
 Are they saying about lending and borrowing money?
 "Our dorm’s budget is 100,000 dollars a year."
 → "Alert: Some people assume your friend’s name. Be sure to
confirm their identity."
 The software should consider comprehensively the words such as $,
dollar, buck, borrow, etc.
 Natural language processing
NateOn: Alert Application
Application 3:
Context-driven Advertisement
Application 3
 If we can figure out the
context or theme of a
dialogue, we can apply an
advertisement to the
dialogue.
Business model:
Messengers
Business model - Messengers
 Technical Aspects
 Socket programming
 Dialogue and presentation layer protocols are added.
 Multi-threading
 GUI (Graphical User Interface) (Windows)
 Business Aspects
 To make money from a messenger service itself
 Functionality and advertisement
 To make money from a wider service which contains a
messenger service as a part of a wider service
 Functionality
NateOn & Windows Live Messenger
Skype
Building Blocks for Network
Programming
Building Block: Server Sockets
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
…
… String request = input.readLine();
…
… output.println("Response from server");
…
output.close();
Receive
input.close();
clientConn.close();
serverSocket.close();
Send
} catch (Exception e) {
System.err.println(e);
}
Building Block: Client Sockets
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
…
…output.println("Request from client");
…
… String response = input.readLine();
…
output.close();
Send
input.close();
socket.close();
Receive
} catch (Exception e) {
System.err.println(e);
}
Building Block: if statement
 Syntax
if (expression) {
statement(s)1
} else {
statement(s)2
}
 Control and execution
 If evaluation result of the
"expression" is true, then
"statement(s)1" is executed.
 Otherwise, "statement(s)2" is
executed.
 e.g.
if (n > 0) {
a = 1;
} else {
a = 0;
}
Building Block: for statement
 Syntax
for (expression1; expression2;
expression3) {
statement(s)
}
 Control and execution
 The "expression1" is evaluated.
 If evaluation result of the
"expression2" is true, then
"statement(s)" is executed.
 After the execution, the
"expression3" is evaluated.
 Go to the evaluation of the
"expression2".
 Otherwise, the whole "for"
statement is finished.
 e.g.
for (i = 0; i < 100; i++)
{
System.out.println(i);
}
Building Block: Standard Output
 Syntax
 void System.out.print(Object)
 void System.out.println(Object)
 e.g.
System.out.print("String");
System.out.print(123);
System.out.println("String");
System.out.println(123);
 The command "print" does not print out an EOLN(i.e.
[Enter]) character.
Building Block: Standard Input
 Syntax
 BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
 String BufferedReader.readLine( ) throws IOException
 e.g.
import java.io.*;
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String str = reader.readLine();
System.out.print("You typed - ");
System.out.println(str);
} catch (Exception e) {
System.err.println(e);
}
Building Block: Multi-threading
Thread
public class MyThread
implements Runnable
{
public String m_msg;
public MyThread() {
m_msg = "";
}
…
public void run() {
m_msg = "message to the
Main";
…
}
…
}
Main
MyThread myThread = new
MyThread(…);
Thread m_thread = new
Thread(myThread);
m_thread.start( );
…
myThread.m_msg =
"message to the thread";
Building Block: Thread.sleep Method
 e.g.
try {
...
Thread.sleep(500);
...
} catch (Exception e) {
System.err.println(e);
}
Building Block: Java Libraries
 String.contains(substring)
 e.g. boolean b = request.contains("love");
 String.equals(string)
 e.g. boolean b = request.equals("Q");
 String.replaceFirst(string, string)
 e.g. String newStr = str.replaceFirst("old part", "new part");
 String.isEmpty( )
 e.g. boolean b = str.isEmpty();
 Integer.parseInt(string)
 e.g. int d = Integer.parseInt("3095");
Exercises
Exercise (1)
 Exercise
 Make client and server programs such that:
 The client inputs two strings from the user and sends them to the server.
 The server receives both of the strings and prints them out.
 Project names
 Client - TCPIPX1Client
 Server - TCPIPX1Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of
server to each student respectively. After testing, switch the roles and
do the same things again.
 Something wrong?
 Try to use the debugger.
Exercise (1) TCPIPX1Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String request1 = reader.readLine();
String request2 = reader.readLine();
output.println(request1);
output.println(request2);
output.close();
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
Exercise (1) TCPIPX1Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
String request1 = input.readLine();
String request2 = input.readLine();
System.out.println(request1);
System.out.println(request2);
output.close();
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
Exercise (2)
 Exercise
 Make client and server programs such that:
 The client inputs two strings from the user and sends them to the server.
 The server receives both of the strings, concatenates them into a string, and sends back
the concatenated string. (Hint: + operator)
 The client receives the string and prints it out.
 Project names
 Client - TCPIPX2Client
 Server - TCPIPX2Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to
each student respectively. After testing, switch the roles and do the same
things again.
 Something wrong?
 Try to use the debugger.
Exercise (2) TCPIPX2Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String request1 = reader.readLine();
String request2 = reader.readLine();
output.println(request1);
output.println(request2);
String response = input.readLine();
System.out.println(response);
output.close();
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
Exercise (2) TCPIPX2Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
String request1 = input.readLine();
String request2 = input.readLine();
String response = request1 + request2;
output.println(response);
output.close();
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
Exercise (3)
 Exercise
 Make client and server programs such that:
 The client inputs multiple strings from the user and sends them to the server.
 The server receives the strings and prints them out.
 Note) An empty string designates the end of the strings. (Hint: String.isEmpty( ))
 Project names
 Client - TCPIPX3Client
 Server - TCPIPX3Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to
each student respectively. After testing, switch the roles and do the same
things again.
 Something wrong?
 Try to use the debugger.
Exercise (3) TCPIPX3Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String request = " ";
for (; request.isEmpty() == false;) {
request = reader.readLine();
output.println(request);
}
output.close();
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
Exercise (3) TCPIPX3Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
String request = " ";
for (; request.isEmpty() == false;) {
request = input.readLine();
System.out.println(request);
}
output.close();
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
Exercise (4)
 Exercise
 Make client and server programs such that:
 The client inputs multiple strings from the user and sends them to the server.
 The server receives the strings , concatenates them into a string, and sends back the
concatenated string.
 The client receives the string and prints it out.
 Note) An empty string designates the end of the strings. (Hint: String.isEmpty( ))
 Project names
 Client - TCPIPX4Client
 Server - TCPIPX4Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to
each student respectively. After testing, switch the roles and do the same things
again.
 Something wrong?
 Try to use the debugger.
Exercise (4) TCPIPX4Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String request = " ";
for (; request.isEmpty() == false;) {
request = reader.readLine();
output.println(request);
}
String response = input.readLine();
System.out.println(response);
output.close();
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
Exercise (4) TCPIPX4Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
String request = " ";
String response = "";
for (; request.isEmpty() == false;) {
request = input.readLine();
response = response + request;
}
output.println(response);
output.close();
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
Exercise (5)
 Exercise
 Make a Java program such that:
 Create a thread, which inputs strings from the standard input and sends
the strings to the main method repeatedly.
 The main method prints out repeatedly the last string sent from the
thread.
 If the last input string is "Q", the thread and the main method stops.
 Project name
 TCPIPX5
Exercise (5) TCPIPX5.Main
try {
MyThread myThread = new MyThread();
Thread m_thread = new Thread(myThread);
m_thread.start();
for (; myThread.m_msg.equals("Q") == false;) {
System.out.println(myThread.m_msg);
Thread.sleep(500);
}
} catch (Exception e) {
System.err.println(e);
}
Exercise (5) TCPIPX5.MyThread
import java.io.*;
public class MyThread implements Runnable {
String m_msg;
public MyThread() {
m_msg = "";
}
public void run() {
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
for (; m_msg.equals("Q") == false;) {
m_msg = reader.readLine();
}
} catch (Exception e) {
System.err.println(e);
}
}
}
Exercise (6)
 Exercise
 Make a Java program such that:
 Create a thread, which calculates the summation from 1 to 1,000,000.
 While calculating the sum, the thread sends to the main method its status
in the form of "#Iteration - Sum at that point" every iterations.
 After finishing the calculation, the thread sends to the main method the
result in the form of "Result - Sum", and stops.
 On the other hand, the main method inputs a string from the standard
input and prints out the last string from the thread. This process is
repeated until the string from the standard input is "Q".
 If the string from the standard input is "Q", the thread also stops.
 Project name
 TCPIPX6
Exercise (6) TCPIPX6.Main
import java.io.*;
try {
MyThread myThread = new MyThread();
Thread m_thread = new Thread(myThread);
m_thread.start();
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String str = " ";
for (; myThread.m_bStop == false && str.equals("Q") == false;) {
str = reader.readLine();
System.out.println(myThread.m_msg);
}
myThread.m_bStop = true;
} catch (Exception e) {
System.err.println(e);
}
Exercise (6) TCPIPX6.MyThread
public class MyThread implements Runnable {
public String m_msg;
public boolean m_bStop;
public MyThread() {
m_msg = "";
m_bStop = false;
}
public void run() {
try {
int i;
int s = 0;
for (i = 1; m_bStop == false && i <= 1000000; i++) {
s = s + i;
m_msg = "#" + i + " - " + s;
Thread.sleep(1);
}
m_msg = "Result - " + s;
System.out.println("Thread finished.");
m_bStop = true;
} catch (Exception e) {
System.err.println(e);
}
}
}
Exercise (6.1)
 Exercise
 Make a Java program such that:
 Create a thread, which calculates the summation from 1 to 1,000,000.
 While calculating the sum, the thread sends to the main method its status
in the form of "#Iteration - Sum at that point" every 100 iterations.
 After finishing the calculation, the thread sends to the main method the
result in the form of "Result - Sum", and stops.
 The main method receives those strings and prints them out every 500
ms. If one of those strings contains "Result -", the main method stops.
 Project name
 TCPIPX61
Exercise (6.1) TCPIPX61.Main
try {
MyThread myThread = new MyThread();
Thread m_thread = new Thread(myThread);
m_thread.start();
for (; myThread.m_msg.contains("Result -") == false;) {
System.out.println(myThread.m_msg);
Thread.sleep(500);
}
System.out.println(myThread.m_msg);
} catch (Exception e) {
System.err.println(e);
}
Exercise (6.1) TCPIPX61.Thread
public class MyThread implements Runnable {
public String m_msg;
public MyThread() {
m_msg = "";
}
public void run() {
try {
int i;
int s = 0;
for (i = 1; i <= 1000000; i++) {
s = s + i;
m_msg = "#" + i + " - " + s;
Thread.sleep(1);
}
m_msg = "Result - " + s;
} catch (Exception e) {
System.err.println(e);
}
}
}
Exercise (7)



Exercise
 Make client and server programs such that:
 The client inputs an integer (in string form) from the user, and sends the string to the server.
 The server converts the string into an integer (Hint: Integer.parseInt(String)) and calculates the
cumulative sum of the numbers from 1 through that integer.
 While calculating the sum, the server sends to the client its status in the form of "#Iteration - Sum at that
point" every 100 iterations.
 After finishing the calculation, the server sends to the client the result in the form of "Result - Sum", and
stops.
 The client receives those strings and prints them out. If one of those strings contains "Result -", the client
stops.
 Project names
 Client - TCPIPX7Client
 Server - TCPIPX7Server
Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to each student respectively. After
testing, switch the roles and do the same things again.
Something wrong?
 Try to use the debugger.
Exercise (7) TCPIPX7Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String request = reader.readLine();
output.println(request);
String response = "";
for (; response.contains("Result -") == false;) {
response = input.readLine();
System.out.println(response);
}
output.close();
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
Exercise (7) TCPIPX7Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
String request = input.readLine();
String response;
int i;
int n = Integer.parseInt(request);
int s = 0;
for (i = 1; i <= n; i++) {
s = s + i;
if (i % 100 == 0) {
response = "#" + i + " - " + s;
output.println(response);
}
Thread.sleep(1);
}
response = "Result - " + s;
output.println(response);
output.close();
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
Exercise (8)

Exercise
 Make client and server programs such that:
 The client inputs an integer (in string form) from the user, and sends the string to the server.
 The server converts the string into an integer (Hint: Integer.parseInt(String)).
 The server creates a thread and makes the thread calculate the cumulative sum of the numbers from 1 through
that integer.
 While calculating the sum, the thread sends to the server its status in the form of "#Iteration - Sum at that point"
every 100 iterations.
 After finishing the calculation, the thread sends to the server the result in the form of "Result - Sum", and stops.
 The server sends to the client those strings from thread every 500 ms. If one of those strings contains "Result -",
the server stops.
 The client receives the strings and prints them out. If one of the strings contains "Result -", the client stops.
 Project names
 Client - TCPIPX8Client
 Server - TCPIPX8Server

Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to each student respectively.
After testing, switch the roles and do the same things again.

Something wrong?
 Try to use the debugger.
Exercise (8) TCPIPX8Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String request = reader.readLine();
output.println(request);
String response = "";
for (; response.contains("Result -") == false;) {
response = input.readLine();
System.out.println(response);
}
output.close();
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
Exercise (8) TCPIPX8Server.Main
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
MyThread myThread = new MyThread();
String str = input.readLine();
myThread.m_n = Integer.parseInt(str);
Thread m_thread = new Thread(myThread);
m_thread.start();
for (; myThread.m_msg.contains("Result -") == false;) {
output.println(myThread.m_msg);
Thread.sleep(500);
}
output.println(myThread.m_msg);
output.close();
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
Exercise (8) TCPIPX8Server.MyThread
public class MyThread implements Runnable {
public String m_msg;
public int m_n;
public MyThread() {
m_msg = "";
m_n = 0;
}
public void run() {
try {
int i;
int s = 0;
for (i = 1; i < m_n; i++) {
s = s + i;
if (i % 100 == 0) {
m_msg = "#" + i + " - " + s;
}
Thread.sleep(1);
}
m_msg = "Result - " + s;
} catch (Exception e) {
System.err.println(e);
}
}
}
Examinations
Examination (1)
 Examination
 Make client and server programs such that:
 The client inputs a string from its standard input and sends it to the server.
 The server receives the string and prints it out to its standard output.
 The server inputs another string from its standard input and sends it to the client.
 The client receives the string and prints it out to its standard output.
 Project names
 Client - EM01Client
 Server - EM01Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to
each student respectively. After testing, switch the roles and do the same
things again.
 Something wrong?
 Try to use the debugger.
Examination (1) EM01Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
System.out.print("Input> ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String request = reader.readLine();
output.println(request);
String response = input.readLine();
System.out.println("Server> " + response);
output.close();
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
Examination (1) EM01Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
String request = input.readLine();
System.out.println("Client> " + request);
System.out.print("Input> ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String response = reader.readLine();
output.println(response);
output.close();
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
Examination (2)
 Examination
 Make client and server programs such that:
 The client inputs multiple strings from its standard input and sends them to the server. An
empty string designates the end of those strings.
 The client inputs one more string from its standard input and sends it to the server, too.
 The server receives and prints out all of those strings.
 Project names
 Client - EM02Client
 Server - EM02Server
 Testing Scenarios
 Run both of client and server program on your own computer.
 Make a group of two students and assign a role of client and that of server to
each student respectively. After testing, switch the roles and do the same things
again.
 Something wrong?
 Try to use the debugger.
Examination (2) EM02Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String request = " ";
for (; request.isEmpty() == false;) {
request = reader.readLine();
output.println(request);
}
request = reader.readLine();
output.println(request);
output.close();
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
Examination (2) EM02Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
String request = " ";
for (; request.isEmpty() == false;) {
request = input.readLine();
System.out.println(request);
}
request = input.readLine();
System.out.println(request);
output.close();
input.close();
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
Examination (3)
 Examination
 Make a Java program such that:
 The main method inputs an integer (in string format) from its standard
input, converts the integer in string format into an integer, and creates a
thread.
 The main method calculates the summation from 1 through that integer.
 While calculating the sum, the main method sends to the thread its status
in the form of "#Iteration - Sum at that point" every 100 iterations.
 After finishing the calculation, the main method sends to the thread the
result in the form of "Result - Sum", and stops.
 The thread receives those strings and prints them out every 500 ms. If
anyone of those strings contains "Result -", the thread stops.
 Project name
 EM03
Examination (3) EM03.Main
import java.io.*;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String str = reader.readLine();
int n = Integer.parseInt(str);
MyThread myThread = new MyThread();
Thread m_thread = new Thread(myThread);
m_thread.start();
int i;
int s = 0;
for (i = 1; i <= n; i++) {
s = s + i;
if (i % 100 == 0) {
myThread.m_msg = "#" + i + " - " + s;
}
Thread.sleep(1);
}
myThread.m_msg = "Result - " + s;
} catch (Exception e) {
System.err.println(e);
}
Examination (3) EM03.MyThread
public class MyThread implements Runnable {
public String m_msg;
public MyThread() {
m_msg = "";
}
}
public void run() {
try {
for (; m_msg.contains("Result -") == false;) {
System.out.println(m_msg);
Thread.sleep(500);
}
System.out.println(m_msg);
} catch (Exception e) {
System.err.println(e);
}
}
Examination (4)
 Examination
 Make a Java program such that:
 The main method inputs an integer (in string format) from its standard input, converts the





integer in string format into an integer, creates a thread, and then sends the integer to the
thread.
The thread calculates the cumulative sum of the numbers from 1 through that integer.
While calculating, the thread prints out its status in the form of "#Iteration - Sum at that
point" every 100 iterations. After calculation, the thread prints out the result in the form of
"Result - Sum", sends a stop message to the main method, and stops.
For the every iteration of the calculation, the thread sleeps for a certain amount of
milliseconds. The initial value of the amount is 5. However, the amount is changed according
to messages from the main method. It is explained below.
The main method inputs repeatedly integers (in string format) from its standard input,
converts them into integers and sends the integers to the thread. The last one among those
integers are used as the amount of milliseconds for the sleep.
While inputing integers, the main method also checks the stop message from the thread. If a
stop message is received, the main method stops.
 Project name
 EM04
Examination (4) EM04.Main
import java.io.*;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String str = reader.readLine();
int n = Integer.parseInt(str);
MyThread myThread = new MyThread();
myThread.m_n = n;
Thread m_thread = new Thread(myThread);
m_thread.start();
for (; myThread.m_bStop == false;) {
str = reader.readLine();
n = Integer.parseInt(str);
myThread.m_sleep = n;
}
} catch (Exception e) {
System.err.println(e);
}
Examination (4) EM04.MyThread
public class MyThread implements Runnable {
public int m_n;
public int m_sleep;
public boolean m_bStop;
public MyThread() {
m_n = 0;
m_sleep = 5;
m_bStop = false;
}
public void run() {
try {
int i;
int s = 0;
for (i = 1; i <= m_n; i++) {
s = s + i;
Thread.sleep(m_sleep);
if (i % 100 == 0) {
System.out.println("#" + i + " - " + s);
}
}
System.out.println("Result - " + s);
m_bStop = true;
} catch (Exception e) {
System.err.println(e);
}
}
}