1、编写服务器用到的知识点
1) Socket 编程
2) HTML
3) HTTP 协议
4) 反射
5) XML 解析
6) 服务器编写
2、复习 Socket 编程
1) C/S 结构:客户端与服务器端一次双向通信
客户端:
public class Client {
public static void main(String[] args) {
System.out.println("------------客户端------------");
Socket client = null;
DataOutputStream dos = null;
DataInputStream dis = null;
try {
//(1)创建Socket对象
client = new Socket("localhost", 8888);
//(2)获取输出流--->向服务器发送请求
dos = new DataOutputStream(client.getOutputStream());
dos.writeUTF("你好服务器,我是客户端!");
//(3)获取输入流--->接收服务器响应
dis = new DataInputStream(client.getInputStream());
System.out.println(dis.readUTF());
} catch (IOException e) {
e.printStackTrace();
}finally {
//(4)关闭流
IOUtil.closeAll(dis, dos, client);
}
}
}
服务器:
public class Server {
public static void main(String[] args) {
System.out.println("------------服务器------------");
ServerSocket server = null;
Socket socket = null;
DataInputStream dis = null;
DataOutputStream dos = null;
try {
//(1)创建ServerSocket对象
server = new ServerSocket(8888);
//(2)监听是否有客户端发送请求,并获取Socket对象
socket = server.accept();
//(3)获取输入流--->获取客户端请求
dis = new DataInputStream(socket.getInputStream());
System.out.println(dis.readUTF());
//(4)获取输出流--->给客户端发送响应
dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("客户端你好:我是服务器,我已收到你的请求!");
} catch (IOException e) {
e.printStackTrace();
}finally {
//(5)关闭流
IOUtil.closeAll(dos, dis, socket, server);
}
}
}
工具类:
public class IOUtil {
//关闭全部流
public static void closeAll(Closeable... clo) {
for (Closeable closeable : clo) {
if(closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
2) B/S 结构:浏览器与服务器
输入网址进行测试:http://localhost:8888/index.html
public class HttpServer {
public static void main(String[] args) {
System.out.println("------------服务器------------");
ServerSocket server = null;
Socket socket = null;
BufferedReader br = null;
try {
//(1)创建ServerSocket对象
server = new ServerSocket(8888);
//(2)监听是否有客户端发送请求,并获取Socket对象
socket = server.accept();
//(3)获取来自浏览器的请求信息
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = null;
while((str = br.readLine()).length() > 0) {
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//(5)关闭流
IOUtil.closeAll(br, socket, server);
}
}
}
运行结果:
尚学堂百战程序员
百战程序员_IT6000集_影响6000万学习IT的中国人【官网】