666,InetAddress
package ;
import ;
import ;
public class API {
public static void main(String[] args) throws UnknownHostException {
//1,Get local InetAddress object getLocalHost
InetAddress localHost = ();
(localHost);//Little Boat's Spaceship/10.150.216.219
//2, according to the specified host name / domain name to get ip address object getByName
InetAddress host1 = ("Little Boat's spaceship"));
("host1= " + host1);//Little Boat's Spaceship/10.150.216.219
//3,According to the domain name return InetAddress object, such as corresponds to
InetAddress host2 = ("");
("host2= " + host2);///220.181.38.149
//4,Get the corresponding address through the InetAddress object.
String hostAddress = ();
("host2 corresponds to ip= " + hostAddress).//220.181.38.149
//5, through the InetAddress object, get the corresponding host name / or domain name
String hostName = ();
("host2 corresponds to hostname/domain name = " + hostName).//
}
}
668, TCP Byte Stream Programming 1
Thoughts:
The client writes data out of memory onto the data channel, and then the server reads data from the data channel into memory
Code:
Server-side code:
package ;
import ;
import ;
import ;
import ;
//server-side
public class SocketTCP01Server {
public static void main(String[] args) throws IOException {
//reasoning
//1. Listen on port 9999 of the local machine, waiting for a connection
// Details: Requires that no other services are listening on this machine 9999
// Details: This ServerSocket can return multiple Sockets via accept() [multiple clients connecting to the server concurrently].
ServerSocket serverSocket = new ServerSocket(9999);
("Server, listening on port 9999, waiting for connection...");
//2. when no client connects to port 9999, the program blocks and waits for a connection.
// If a client connects, the Socket object is returned and the program continues.
Socket socket = ();
("socket = " + ());
//3. Read the data written to the data channel by the client through (), show
InputStream inputStream = ();
//4. IO reading
byte[] buf = new byte[1024];
int readLen = 0;
while ((readLen = (buf)) != -1) {
(new String(buf, 0, readLen));
}
//5,Close streams and sockets
();
();
();//cloture
}
}
Client-side code:
package ;
import ;
import ;
import ;
import ;
import ;
//Client, send "hello, server" to the server.
public class SocketTCP01Client {
public static void main(String[] args) throws IOException {
//reasoning
//1. Connect to server (ip , port)
//Interpretation: Connect to local port 9999, if the connection is successful, return the socket object
Socket socket = new Socket((), 9999);
("Client socket returned = " + ());
//2. Once connected, generate a socket, by ()
// Get the output stream object associated with the socket object.
OutputStream outputStream = ();
//3. Write data to the data channel through the output stream.
("hello, server".getBytes());
//4. Close the stream object and socket, must be closed.
();
();
("Client exit");
}
}
Run the server-side code first, then run the client-side code, and the results of the two codes are as follows:
669, TCP Byte Stream Programming 2
Thoughts:
One more step than in the previous case: the server writes the data to be sent from memory to the data channel.
Code:
Server-side code:
package ;
import ;
import ;
import ;
import ;
import ;
public class SocketTCP02Server {
public static void main(String[] args) throws IOException {
//reasoning
//1. Listen on port 9999 of the local machine, waiting for a connection
// Details: Requires that no other services are listening on this machine 9999
// Details: This ServerSocket can return multiple Sockets via accept() [multiple clients connecting to the server concurrently].
ServerSocket serverSocket = new ServerSocket(9999);
("Server, listening on port 9999, waiting for connection...");
//2. when no client connects to port 9999, the program blocks and waits for a connection.
// If a client connects, the Socket object is returned and the program continues.
Socket socket = ();
("socket = " + ());
//3. Read the data written to the data channel by the client through (), show
InputStream inputStream = ();
//4. IO reading
byte[] buf = new byte[1024];
int readLen = 0;
while ((readLen = (buf)) != -1) {
(new String(buf, 0, readLen));
}
//5, Get the output stream associated with the socket
OutputStream outputStream = ();
("hello, client".getBytes());
//Setting the End Marker
();
//6,Close streams and sockets
();
();
();
();//cloture
}
}
Client-side code:
package ;
import ;
import ;
import ;
import ;
import ;
@SuppressWarnings({"all"})
public class SocketTCP02Client {
public static void main(String[] args) throws IOException {
//reasoning
//1. Connect to server (ip , port)
//Interpretation: Connect to local port 9999, if the connection is successful, return the socket object
Socket socket = new Socket((), 9999);
("Client socket returned = " + ());
//2. Once connected, generate a socket, by ()
// Get the output stream object associated with the socket object.
OutputStream outputStream = ();
//3. Write data to the data channel through the output stream.
("hello, server".getBytes());
//Setting the End Marker
();
//4. Get the input stream associated with the socket, read the data (bytes), and display it
InputStream inputStream = ();
byte[] buf = new byte[1024];
int readLen = 0;
while ((readLen = (buf)) != -1) {
(new String(buf, 0, readLen));
}
//5. Close the stream object and socket, must be closed.
();
();
();
("Client exit");
}
}
Run results:
670, TCP Character Stream Programming
Thoughts:
Code:
Server-side code:
package ;
import .*;
import ;
import ;
public class SocketTCP03Server {
public static void main(String[] args) throws IOException {
//reasoning
//1. Listen on port 9999 of the local machine, waiting for a connection
// Details: Requires that no other services are listening on this machine 9999
// Details: This ServerSocket can return multiple Sockets via accept() [multiple clients connecting to the server concurrently].
ServerSocket serverSocket = new ServerSocket(9999);
("Server, listening on port 9999, waiting for connection...");
//2. when no client connects to port 9999, the program blocks and waits for a connection.
// If a client connects, the Socket object is returned and the program continues.
Socket socket = ();
("socket = " + ());
//3. Read the data written to the data channel by the client through (), show
InputStream inputStream = ();
//4. IO reads, using character streams, the teacher uses InputStreamReader to convert the inputStream into a character stream.
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String s = ();
(s);//exports
//5, Get the output stream associated with the socket
OutputStream outputStream = ();
// Replying to messages using a character output stream
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
("hello client character stream.");
();
();//Note that a manual flush is required
//Setting the End Marker
();
//6,Close streams and sockets
();
();
();
();//cloture
}
}
Client-side code:
package ;
import .*;
import ;
import ;
public class SocketTCP03Client {
public static void main(String[] args) throws IOException {
//reasoning
//1. Connect to server (ip , port)
//Interpretation: Connect to local port 9999, if the connection is successful, return the socket object
Socket socket = new Socket((), 9999);
("Client socket returned = " + ());
//2. Once connected, generate a socket, by ()
// Get the output stream object associated with the socket object.
OutputStream outputStream = ();
//3. Write data to the data channel via the output stream, using the character stream.
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
("hello, server character stream.");
();// Insert a newline character to indicate the end of the reply, note that the other party is required to use readLine().
();//If you are using a character stream, you need to manually refresh it, otherwise the data will not be written to the data channel
//Setting the End Marker
();
//4. Get the input stream associated with the socket, read the data (characters), and display it.
InputStream inputStream = ();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String s = ();
(s);
//5. Close the stream object and socket, must be closed.
();//Closing the outer stream
();
();
("Client exit");
}
}
Run results:
671, Network uploading of files
Thoughts:
Unlike the previous question, the client has to read the picture into memory first, and then write out the picture from memory to the data channel; the server reads the picture's data from the data channel into its own computer's memory, and then writes it out of memory to the disk directory where it's stored; and the server writes the information about the picture it received to the data channel, and then the client reads it back in.
Code:
StreamUtils Class
package ;
import ;
import ;
import ;
import ;
import ;
/**
* :: This class is used to demonstrate methods for reading and writing about streams
*
*/
public class StreamUtils {
/**
* Function: Converts the input stream to byte[], i.e., the contents of the file can be read into byte[].
*@param is
* @return
* @throws Exception
*/
public static byte[] streamToByteArray(InputStream is) throws Exception{
ByteArrayOutputStream bos = new ByteArrayOutputStream();//Creating an Output Stream Object
byte[] b = new byte[1024];//byte array
int len;
while((len=(b))!=-1){//Cyclic reading
(b, 0, len);//Write the read data to bos.
}
byte[] array = ();//Then convert the bos to a byte array
();
return array;
}
/**
* Function: Convert InputStream to String
*@param is
* @return
* @throws Exception
*/
public static String streamToString(InputStream is) throws Exception{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder= new StringBuilder();
String line;
while((line=())!=null){
(line+"\r\n");
}
return ();
}
}
Server-side code:
package ;
import .*;
import ;
import ;
//Server for file uploads
public class TCPFileUploadServer {
public static void main(String[] args) throws Exception {
//1. Server listening on port 8888 locally
ServerSocket serverSocket = new ServerSocket(8888);
("Server listening on port 8888 ....");
//2. Waiting for connections
Socket socket = ();
//3. Read the data sent by the client
// Getting Input Streams via Sockets
BufferedInputStream bis = new BufferedInputStream(());
byte[] bytes = (bis);
//4. will get bytes array, write to the specified path, you will get a file
String destFilePath = "src\\";
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
(bytes);
();
// Reply to the client "Receive picture"
// Getting the output stream (characters) via socket
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(()));
("Pictures received.");
();//Refresh the content to the data channel
();//Setting the end-of-write flag
//Closure of other resources
();
();
();
();
}
}
Client-side code
package ;
import .*;
import ;
import ;
import ;
//Client for file uploads
public class TCPFileUploadClient {
public static void main(String[] args) throws Exception {
//Client connects to server 8888, gets Socket object
Socket socket = new Socket((), 8888);
//Creating an input stream to read a disk file
//String filePath = "e:\\";
String filePath = "d:\\";
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
//bytes is the byte array corresponding to filePath.
byte[] bytes = (bis);
//Get the output stream via socket, send bytes to the server.
BufferedOutputStream bos = new BufferedOutputStream(());
(bytes);//Write the contents of the corresponding byte array of the file to the data channel.
();
();//Setting the end flag for writing data
//===== receives messages replied from the server =====
InputStream inputStream = ();
//Use the StreamUtils method to convert the content of the inputStream to a string.
String s = (inputStream);
(s);
//Close the associated stream
();
();
();
}
}
Run results:
677, UDP Network Programming 1
Thoughts:
Code:
Code on the receiving end:
package ;
import ;
import ;
import ;
import ;
import ;
//UDP Receiver
public class UDPReceiverA {
public static void main(String[] args) throws IOException {
//1. Create a DatagramSocket object, ready to receive data at 9999
DatagramSocket socket = new DatagramSocket(9999);
//2. Build a DatagramPacket object, ready to receive data
// When explaining the UDP protocol, the teacher said that the maximum size of a packet is 64k.
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, );
//3. Call the Receive method, and send the DatagramPacket object transmitted over the network to the
// Fill to packet object
//Teacher's Tip: Data is received when a packet is sent to port 9999 on this machine.
// If no packets are sent to port 9999 on the local machine, it will block and wait.
("Receiver A waiting to receive data..."));
(packet);
//4. You can unpack the packet, remove the data, and display it.
int length = ();//Actual received data byte length
byte[] data = ();//Receiving data
String s = new String(data, 0, length);
(s);
//===Reply message to B
//Encapsulate the data to be sent into a DatagramPacket object.
data = "Okay, see you tomorrow.".getBytes();
//Description: Encapsulated DatagramPacket object data content byte array , , host (IP) , port
packet =
new DatagramPacket(data, , ("192.168.191.221"), 9998);
(packet);//dispatch
//5. Closure of resources
();
("A-side exit...");
}
}
Code on the sending side:
package ;
import ;
import .*;
//Transmitter B ====> can also receive data
public class UDPSenderB {
public static void main(String[] args) throws IOException {
//1. Create a DatagramSocket object ready to receive data on port 9998.
DatagramSocket socket = new DatagramSocket(9998);
//2. Encapsulate the data to be sent into a DatagramPacket object.
byte[] data = "hello Fondue tomorrow~".getBytes();
//Description: Encapsulated DatagramPacket object data content byte array , , host (IP) , port
DatagramPacket packet =
new DatagramPacket(data, , ("192.168.191.221"), 9999);
(packet);
//3.=== Receive the message from A.
//(1) Construct a DatagramPacket object ready to receive data.
// When explaining the UDP protocol, the teacher said that the maximum size of a packet is 64k.
byte[] buf = new byte[1024];
packet = new DatagramPacket(buf, );
//(2) Call the Receive method, and send the DatagramPacket object transmitted over the network to
// Fill to packet object
//Teacher's Note: Data is received when a packet is sent to port 9998 on this machine.
// If no packets are sent to the local port 9998, it will block and wait.
(packet);
//(3) You can unpack the packet, remove the data, and display it.
int length = ();//Actual received data byte length
data = ();//Receiving data
String s = new String(data, 0, length);
(s);
//Close resource
();
("B-side exit.");
}
}
Run results:
679, Network Programming Assignment 1
Code:
Just take the code from section 670 and change it.
Server-side code:
package ;
import .*;
import ;
import ;
@SuppressWarnings({"all"})
public class Homework01Server {
public static void main(String[] args) throws IOException {
//reasoning
//1. Listen on port 9999 of the local machine, waiting for a connection
// Details: Requires that no other services are listening on this machine 9999
// Details: This ServerSocket can return multiple Sockets via accept() [multiple clients connecting to the server concurrently].
ServerSocket serverSocket = new ServerSocket(9999);
("Server, listening on port 9999, waiting for connection...");
//2. when no client connects to port 9999, the program blocks and waits for a connection.
// If a client connects, the Socket object is returned and the program continues.
Socket socket = ();
//3. Read the data written to the data channel by the client through (), show
InputStream inputStream = ();
//4. IO reads, using character streams, the teacher uses InputStreamReader to convert the inputStream into a character stream.
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String s = ();
String answer = "";
if ("name".equals(s)) {
answer = "I'm Han Soon-pyeong.";
} else if ("hobby".equals(s)) {
answer = "Writing java programs";
} else {
answer = "What are you talking about?";
}
//5, Get the output stream associated with the socket
OutputStream outputStream = ();
// Replying to messages using a character output stream
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
(answer);
();
();//Note that a manual flush is required
//Setting the End Marker
();
//6,Close streams and sockets
();
();
();
();//cloture
}
}
Client-side code:
package ;
import .*;
import ;
import ;
import ;
@SuppressWarnings({"all"})
public class Homework01Client {
public static void main(String[] args) throws IOException {
//reasoning
//1. Connect to server (ip , port)
//Interpretation: Connect to local port 9999, if the connection is successful, return the socket object
Socket socket = new Socket((), 9999);
("Client socket returned = " + ());
//2. Once connected, generate a socket, by ()
// Get the output stream object associated with the socket object.
OutputStream outputStream = ();
//3. Write data to the data channel via the output stream, using the character stream.
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
//Problems reading users from the keyboard
Scanner scanner = new Scanner();
("Please enter your question.");
String question = ();
(question);
();// Insert a newline character to indicate the end of the reply, note that the other party is required to use readLine().
();//If you are using a character stream, you need to manually refresh it, otherwise the data will not be written to the data channel
//Setting the End Marker
();
//4. Get the input stream associated with the socket, read the data (characters), and display it.
InputStream inputStream = ();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String s = ();
(s);
//5. Close the stream object and socket, must be closed.
();//Closing the outer stream
();
();
("Client exit");
}
}
Run results:
680, Network Programming Assignment 2
Code:
Take the code from section 677 and change it.
Code on the receiving end:
package ;
import ;
import ;
import ;
import ;
@SuppressWarnings({"all"})
//UDP Receiver
public class Homework02ReceiverA {
public static void main(String[] args) throws IOException {
//1. Create a DatagramSocket object, ready to receive data in 8888
DatagramSocket socket = new DatagramSocket(8888);
//2. Build a DatagramPacket object, ready to receive data
// When explaining the UDP protocol, the teacher said that the maximum size of a packet is 64k.
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, );
//3. Call the Receive method, and send the DatagramPacket object transmitted over the network to the
// Fill to packet object
("Receiving end Waiting to receive question"));
(packet);
//4. You can unpack the packet, remove the data, and display it.
int length = ();//Actual received data byte length
byte[] data = ();//Receiving data
String s = new String(data, 0, length);
//Determine what information is being received
String answer = "";
if ("Which are the Four Greats?".equals(s)) {
answer = "The Four Great Masterpieces: Dream of the Red Chamber, Romance of the Three Kingdoms, Journey to the West, Water Margin.";
} else {
answer = "what?";
}
//===Reply message to B
//Encapsulate the data to be sent into a DatagramPacket object.
data = ();
//Description: Encapsulated DatagramPacket object data content byte array , , host (IP) , port
packet =
new DatagramPacket(data, , ("192.168.191.221"), 9998);
(packet);//dispatch
//5. Closure of resources
();
("A-side exit...");
}
}
Code on the sending side:
package ;
import ;
import ;
import ;
import ;
import ;
@SuppressWarnings({"all"})
//Transmitter B ====> can also receive data
public class Homework02Sender {
public static void main(String[] args) throws IOException {
//1. Create a DatagramSocket object ready to receive data on port 9998.
DatagramSocket socket = new DatagramSocket(9998);
//2. Encapsulate the data to be sent into a DatagramPacket object.
Scanner scanner = new Scanner();
("Please enter your question:");
String question = ();
byte[] data = ();
//Description: Encapsulated DatagramPacket object data content byte array , , host (IP) , port
DatagramPacket packet =
new DatagramPacket(data, , ("192.168.191.221"), 8888);
(packet);
//3.=== Receive the message from A.
//(1) Construct a DatagramPacket object ready to receive data.
// When explaining the UDP protocol, the teacher said that the maximum size of a packet is 64k.
byte[] buf = new byte[1024];
packet = new DatagramPacket(buf, );
//(2) Call the Receive method, and send the DatagramPacket object transmitted over the network to
// Fill to packet object
//Teacher's Note: Data is received when a packet is sent to port 9998 on this machine.
// If no packets are sent to the local port 9998, it will block and wait.
(packet);
//(3) You can unpack the packet, remove the data, and display it.
int length = ();//Actual received data byte length
data = ();//Receiving data
String s = new String(data, 0, length);
(s);
//Close resource
();
("B-side exit.");
}
}
Run results: