vb.net 类监听 socket_手写服务器_Socket知识点回顾

7fecc4a9f557443390e05affdc9ed33b.gif

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);
		}
	}
}

运行结果:

00e90292d35531f5431602656cfba03e.png

尚学堂百战程序员

百战程序员_IT6000集_影响6000万学习IT的中国人【官网】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值