学习了很久的Java网络编程,因为没有实际操作过,所以很久没有总结,但网络编程毕竟是Java系统学习中很重要的一部分,所以今天还是要来总结一下。
Java网络编程是什么
网络编程是指编写运行在多个设备(计算机)的程序,这些设备都通过网络连接起来。java.net包中J2SE的API包含有类和接口,它们提供低层次的通信细节。java.net包中提供了两种常见的网络协议的支持:
TCP
TCP是传输控制协议的缩写,它保障了两个应用程序之间的可靠通信。通常用于互联网协议,被称TCP/IP。
Server
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class Server {
public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(8888); while(true) { Socket socket = server.accept(); System.out.println("客户端建立连接"); String msg = "欢迎使用";
DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeUTF(msg); dos.flush(); } } }
|
Client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class Client {
public static void main(String[] args) throws UnknownHostException, IOException { Socket client = new Socket("localhost",8888);
DataInputStream dis = new DataInputStream(client.getInputStream()); String echo = dis.readUTF(); System.out.println(echo); } }
|
UDP
UDP是用户数据报协议的缩写,一个无连接的协议。提供了应用程序之间要发送的数据的数据包。
Server
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class Server {
public static void main(String[] args) throws IOException { DatagramSocket server = new DatagramSocket(8888); byte[] container = new byte[1024]; DatagramPacket packet = new DatagramPacket(container, container.length); server.receive(packet); byte[] data = packet.getData(); int len = packet.getLength(); System.out.println(new String(data,0,len)); server.close(); } }
|
Client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class Client {
public static void main(String[] args) throws IOException { DatagramSocket client = new DatagramSocket(6666); String msg = "udp编程"; byte[] data = msg.getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length,new InetSocketAddress("localhost",8888)); client.send(packet); client.close(); } }
|
手写网络编程服务器实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| public class Server2 { private ServerSocket server;
public static void main(String[] args) { Server2 server = new Server2(); server.start(); }
public void start() { try { server = new ServerSocket(8888); this.receive(); } catch (IOException e) { e.printStackTrace(); }
} private void receive() { try { Socket client = server.accept();
String msg = null;
byte[] data = new byte[20480];
int len = client.getInputStream().read(data); String requestInfo = new String(data, 0, len).trim(); System.out.println(requestInfo);
} catch (IOException e) { } } public void stop() {
} }
|
在浏览器地址栏输入localhost:8888,访问我们手写的网络服务器,在控制台会输出我们的访问请求信息。
1 2 3 4 5 6 7 8 9 10
| GET / HTTP/1.1 Host: localhost:8888 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*
|