(一)下列程序是使用Socket编写C/S结构网络程序的例子。
package case1;
// 客户端程序
import java.io.*;
import java.net.*;
public class TalkClient {
public static void main(String args[]) {
try {
Socket socket = new Socket("127.0.0.1", 4700);
//
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
//
PrintWriter os = new PrintWriter(socket.getOutputStream());
//
BufferedReader is = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
//
String readline;
readline = sin.readLine(); //
while (!readline.equals("bye")) {
//
os.println(readline);
//
os.flush();
//
System.out.println("Client:" + readline);
//
System.out.println("Server:" + is.readLine());
//
readline = sin.readLine(); //
}
os.close(); //
is.close(); //
socket.close(); //
} catch (Exception e) {
System.out.println("Error" + e); //
}
}
}
package case1;
// 服务器端程序
import java.io.*;
import java.net.*;
import java.applet.Applet;
public class TalkServer {
public static void main(String args[]) {
try {
ServerSocket server = null;
try {
//
server = new ServerSocket(4700);
} catch (Exception e) {
System.out.println("can not listen to:" + e);
//
}
Socket socket = null;
try {
socket = server.accept(); //
} catch (Exception e) {
System.out.println("Error." + e); //
}
String line;
BufferedReader is = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
//
PrintWriter os = new PrintWriter(socket.getOutputStream());
//
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
//
System.out.println("Client:" + is.readLine());
//
line = sin.readLine();
//
while (!line.equals("bye")) {
//
os.println(line);
//
os.flush();
//
System.out.println("Server:" + line);
//
System.out.println("Client:" + is.readLine());
//
line = sin.readLine();
//
}
os.close(); //
is.close(); //
socket.close(); //
server.close(); //
} catch (Exception e) {
System.out.println("Error:" + e);
//
}
}
}
在//注释处补充你对程序的理解。
package case1;
// 客户端程序
import java.io.*;
import java.net.*;
public class TalkClient {
public static void main(String args[]) {
try {
Socket socket = new Socket("127.0.0.1", 4700);
// 向本机的4700端口发出客户请求
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
// 由系统标准输入设备构造BufferedReader对象
PrintWriter os = new PrintWriter(socket.getOutputStream());
// 由Socket对象得到输出流,并构造PrintWriter对象
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// 由Socket对象得到输入流,并构造相应的BufferedReader对象
String readline;
readline = sin.readLine(); // 从系统标准输入读入一字符串
while (!readline.equals("bye")) {
// 若从标准输入读入的字符串为 "bye"则停止循环
os.println(readline);
// 将从系统标准输入读入的字符串输出到Server
os.flush();
// 刷新输出流,使Server马上收到该字符串
System.out.println("Client:" + readline);
// 在系统标准输出上打印读入的字符串
System.out.println("Server:" + is.readLine());
// 从Server读入一字符串,并打印到标准输出上
readline = sin.readLine(); // 从系统标准输入读入一字符串
} // 继续循环
os.close(); // 关闭Socket输出流
is.close(); // 关闭Socket输入流
socket.close(); // 关闭Socket
} catch (Exception e) {
System.out.println("Error" + e); // 出错,则打印出错信息
}
}
}
package case1;
// 服务器端程序
import java.io.*;
import java.net.*;
import java.applet.Applet;
public class TalkServer {
public static void main(String args[]) {
try {
ServerSocket server = null;
try {
server = new ServerSocket(4700); // 创建一个ServerSocket在端口4700监听客户请求
} catch (Exception e) {
System.out.println("can not listen to:" + e);
// 出错,打印出错信息
}
Socket socket = null;
try {
socket = server.accept();
// 使用accept()阻塞等待客户请求,有客户
// 请求到来则产生一个Socket对象,并继续执行
} catch (Exception e) {
System.out.println("Error." + e);
// 出错,打印出错信息
}
String line;
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// 由Socket对象得到输入流,并构造相应的BufferedReader对象
PrintWriter os = new PrintWriter(socket.getOutputStream());
// 由Socket对象得到输出流,并构造PrintWriter对象
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
// 由系统标准输入设备构造BufferedReader对象
System.out.println("Client:" + is.readLine());
// 在标准输出上打印从客户端读入的字符串
line = sin.readLine();
// 从标准输入读入一字符串
while (!line.equals("bye")) {
// 如果该字符串为 "bye",则停止循环
os.println(line);
// 向客户端输出该字符串
os.flush();
// 刷新输出流,使Client马上收到该字符串
System.out.println("Server:" + line);
// 在系统标准输出上打印读入的字符串
System.out.println("Client:" + is.readLine());
// 从Client读入一字符串,并打印到标准输出上
line = sin.readLine();
// 从系统标准输入读入一字符串
} // 继续循环
os.close(); // 关闭Socket输出流
is.close(); // 关闭Socket输入流
socket.close(); // 关闭Socket
server.close(); // 关闭ServerSocket
} catch (Exception e) {
System.out.println("Error:" + e);
// 出错,打印出错信息
}
}
}
(二)下面是一个使用TCP协议通过客户端获取服务器端时间的例子。说明:DatagramSocket类和DatagramPacket类是用来支持数据报通信的两个类,它们位于java.net包中。DatagramSocket类用于建立通信连接,DatagramPacket类用于表示数据报。
用数据报方式编写客户端/服务器程序时,需要先建立一个DatagramSocket对象,用来接收或发送数据报,接下来再使用DatagramPacket类作为数据传输的载体。
package case2;
import java.net.*;
import java.io.*;
public class DateClient {
public static void main(String args[]) {
if (args.length != 1) {
System.out.println("usage: DateClient " );
System.exit(1);
}
String serverName=args[0];
Socket s = null;
try {
//1.create a Socket connection
s=new Socket(serverName,7000);
System.out.println("Client " +
s);
//2. Read (write) with socket
BufferedReader reader;
Reader=new BufferedReader(
New InputStreamReader(
S.getInputStream()));
System.out.println(serverName + " says " +
reader.readLine());
} catch (Exception e) {
System.out.println(e);
} finally{
try{
// 3. close connection
s.close();
}catch(Exception e) {};
}
}
}
package case2;
import java.net.*;
import java.io.*;
import java.util.Date;
public class DateServer {
// int port;
// ServerSocket serverSocket;
public DateServer(int port) throws Exception {
// serverSocket = new ServerSocket(port);
}
public static void main(String[] args) {
// public void run() throws Exception {
// while (true) {
ServerSocket ServerSocket1 = null;
Socket clientSocket = null;
try {
// DateServer ds = new DateServer(7000);
System.out.println("Waiting for a connection...");
// 1. create a socket (accept)
SeverSocket1 = new ServerSocket(7000);
clientSocket = ServerSocket1.accept();
System.out.println("Connected to " +
clientSocket);
// 2. write(read) data
PrintWriter out = new PrintWriter(
new OutputStreamWriter(
clientSocket.getOutputStream()));
Date date = new Date();
out.println(date.toString());
out.close();
// }
} catch (Exception e) {
} finally {
try {
// 3. close connection
ServerSocket1.close();
clientSocket.close();
} catch (Exception e) {
}
}
}
}
(三)下面是一个使用UDP协议通过客户端获取服务器端时间的例子。
package case2;
import java.io.*;
import java.net.*;
public class UDPClient {
public void go() throws IOException, UnknownHostException {
DatagramSocket datagramSocket;
DatagramPacket outDataPacket; // Datagram packet to the server
DatagramPacket inDataPacket; // Datagram packet from the server
InetAddress serverAddress; // Server host address
byte[] msg = new byte[100]; // Buffer space.
String receivedMsg; // Received message in String form.
// Allocate a socket by which messages are sent and received.
datagramSocket = new DatagramSocket();
System.out.println("At UDPClient,datagramSocket is: "
+ datagramSocket.getPort()
+ "local port is: "
+ datagramSocket.getLocalPort());
// Server is running on this same machine for this example.
// This method can throw an UnknownHostException.
serverAddress = InetAddress.getLocalHost();
// Set up a datagram request to be sent to the server.
// Send to port 8000.
outDataPacket = new DatagramPacket(msg, 1, serverAddress, 8000);
// Make the request to the server.
datagramSocket.send(outDataPacket);
// Set up a datagram packet to receive server's response.
inDataPacket = new DatagramPacket(msg, msg.length);
// Receive the time data from the server
datagramSocket.receive(inDataPacket);
// Print the data received from the server
receivedMsg = new String(inDataPacket.getData(), 0, inDataPacket.getLength());
System.out.println(receivedMsg);
// close the socket
datagramSocket.close();
}
public static void main(String args[]) {
UDPClient udpClient = new UDPClient();
try {
udpClient.go();
} catch (Exception e) {
System.out.println("Exception occured with socket.");
System.out.println(e);
System.exit(1);
}
}
}
package case2;
import java.io.*;
import java.net.*;
import java.util.*;
public class UDPServer {
// This method retrieves the current time on the server
public byte[] getTime() {
Date d = new Date();
return d.toString().getBytes();
}
// Main server loop.
public void go() throws IOException {
DatagramSocket datagramSocket;
DatagramPacket inDataPacket; // Datagram packet from the client
DatagramPacket outDataPacket; // Datagram packet to the client
InetAddress clientAddress; // Client return address
int clientPort; // Client return port
byte[] msg = new byte[10]; // Incoming data buffer. Ignored.
byte[] time; // Stores retrieved time
// Allocate a socket to man port 8000 for requests.
datagramSocket = new DatagramSocket(8000);
System.out.println("At UDPServer,datagramSocket is: "
+ datagramSocket.getPort()
+ "local is: " + datagramSocket.getLocalPort());
System.out.println("UDP server active on port 8000");
// Loop forever
while (true) {
// Set up receiver packet. Data will be ignored.
inDataPacket = new DatagramPacket(msg, msg.length);
// Get the message.
datagramSocket.receive(inDataPacket);
// Retrieve return address information, including InetAddress
// and port from the datagram packet just recieved.
clientAddress = inDataPacket.getAddress();
clientPort = inDataPacket.getPort();
// Get the current time.
time = getTime();
// set up a datagram to be sent to the client using the
// current time, the client address and port
outDataPacket = new DatagramPacket(time, time.length, clientAddress, clientPort);
// finally send the packet
datagramSocket.send(outDataPacket);
}
}
public static void main(String args[]) {
UDPServer udpServer = new UDPServer();
try {
udpServer.go();
} catch (IOException e) {
System.out.println("IOException occured with socket.");
System.out.println(e);
System.exit(1);
}
}
}
启动服务端与客户端,运行上述程序查看运行结果
(四)请解释Web开发中的C/S结构和B/S结构。
对比程序(二)和程序(三),查看并说明TCP与UDP在编写程序上的区别。
①TCP是面向连接的协议,以保证传输的可靠性。发送方和接收方的Socket之间需要建立连接,以保证得到的是一个顺序,无差错的数据流。
②UDP是一种无连接协议,因此每个数据报向目的地传送的路径并不固定,它可能通过任何可能的路径到达目的地。①B/S结构统一了客户端,让核心的业务在服务端完成。
(五)TCP/IP协议和UDP/IP协议的主要区别是什么?
②C/S结构是一种软件系统体系结构,这种结构是将需要处理的业务合理地分配到客户端和服务器端。①TCP是面向连接的协议,以保证传输的可靠性。发送方和接收方的Socket之间需要建立连接,以保证得到的是一个顺序,无差错的数据流。一旦两个Socket成功建立连接,它们就可以进行双向数据传输,每一方既可以作为发送方,也可以作为接收方。
(六)使用Socket编程的基本步骤是什么?
②UDP是一种无连接协议,因此每个数据报向目的地传送的路径并不固定,它可能通过任何可能的路径到达目的地。至于每个数据报是否能最终到达以及内容的正确性都是无法保证的。
③对于数据可靠性要求高的数据传输,可以采用TCP;而对于数据可靠性要求不高的情况,则可以选用占用资源较小的UDP。①创建Socket.
(七)用来支持开发TCP/IP网络程序的两个类是什么?
②打开连接到Socket上的I/O流,遵照某种协议对Socket进行读写 *** 作。
③关闭Socket.①Socket类;
(八)用来支持开发UDP/IP网络程序的两个类是什么?
②ServerSocket类。①DatagramSocket类;
②DatagramPacket类。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)