网络编程
UDP
1.基础操作
-
DatagramSocket创建套接字socket 此类表示用于发送和接收数据报包的套接字。
数据报套接字是分组传送服务的发送或接收点。 在数据报套接字上发送或接收的每个数据包都是单独寻址和路由的。 从一台机器发送到另一台机器的多个分组可以被不同地路由,并且可以以任何顺序到达。
-
DatagramPacket 创建数据包dp 该类表示数据报包。
数据报分组用于实现无连接分组传递服务。 每个消息仅根据该数据包中包含的信息从一台机器路由到另一台机器。 从一台机器发送到另一台机器的多个数据包可能会以不同方式路由,并且可能以任何顺序到达。 无法保证数据包传输。
send
package com.internet.UDP; import java.io.IOException; import java.net.*; import java.nio.charset.StandardCharsets; //UDP public class send { public static void main(String[] args) throws IOException { //1.创建发送端的Socket对象 DatagramSocket socket=new DatagramSocket(); //2.创建数据,并把数据打包 //DatagramPacket(byte[] buf, int length, InetAddress address, int port) // 构造一个数据报包,用于将长度为 length的数据包发送到指定主机上的指定端口号。 byte[]bytes="hello,我来了".getBytes(StandardCharsets.UTF_8); int len=bytes.length; InetAddress address = InetAddress.getByName("192.168.137.1"); int port=10010; DatagramPacket dp=new DatagramPacket(bytes,len,address,port); //3.调用DatagramSocket 对象的方法发送数据 //send(DatagramPacket p) 从此套接字发送数据报包。 socket.send(dp); //4.关闭此数据报套接字。 socket.close(); } }
receiver
package com.internet.UDP; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class receive { public static void main(String[] args) throws IOException { //1.创建接收端的Socket对象(DatagramSocket) //DatagramSocket(int port) 构造一个数据报套接字并将其绑定到本地主机上的指定端口。 DatagramSocket socket= new DatagramSocket(10010); //2.创建一个数据包,用于接收数据 //DatagramPacket(byte[] buf, int length) 构造 DatagramPacket用于接收长度为 length数据包。 byte[]bytes=new byte[1024]; DatagramPacket dp=new DatagramPacket(bytes,bytes.length); //3.调用DatagramSocket对象的方法接受数据 socket.receive(dp); //4.解析数据包,并把数据在控制台上显示 byte[] data = dp.getData(); //控制有效长度 int getLength(),数据包对象调用方法查看接收数据的长度; int len=dp.getLength(); String dataString=new String(data,0,len); System.out.println(dataString); /* System.out.println(new String(dp.getData(),0,dp.getLength())); */ //5.关闭接收端 socket.close(); } }
2.UDP实现聊天程序
TalkSend:
package com.internet.UDP.test1;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TalkReceive implements Runnable {
public int port;
public String msgFrom;
DatagramSocket socket = null;
public TalkReceive(int port, String msgFrom) {
this.port = port;
this.msgFrom = msgFrom;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
byte[] bytes = new byte[1024];
int len = bytes.length;
DatagramPacket dp = new DatagramPacket(bytes, len);
socket.receive(dp);
byte[] dpData = dp.getData();
String receiveData = new String(dpData, 0, dp.getLength());
System.out.println(msgFrom + receiveData);
if (receiveData.equals("bye"))
break;
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
Talk Receive
package com.internet.UDP.test1;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TalkReceive implements Runnable {
public int port;
public String msgFrom;
DatagramSocket socket = null;
public TalkReceive(int port, String msgFrom) {
this.port = port;
this.msgFrom = msgFrom;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
byte[] bytes = new byte[1024];
int len = bytes.length;
DatagramPacket dp = new DatagramPacket(bytes, len);
socket.receive(dp);
byte[] dpData = dp.getData();
String receiveData = new String(dpData, 0, dp.getLength());
System.out.println(msgFrom + receiveData);
if (receiveData.equals("bye"))
break;
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
Student
package com.internet.UDP.test1;
public class Student{
public static void main(String[] args) {
new Thread(new TalkSend(7777,"192.168.137.1",8885)).start();
new Thread(new TalkReceive(9998,"老师:")).start();
}
}
Teacher
package com.internet.UDP.test1;
public class Teacher {
public static void main(String[] args) {
//teacher
new Thread(new TalkSend(5555,"192.168.137.1",9998)).start();
new Thread(new TalkReceive(8885,"学生:")).start();
}
}
TCP
1.基础操作
客户端
-
Socket 该类实现客户端套接字(也称为“套接字”)。套接字是两台机器之间通信的端点。
套接字的实际工作由
SocketImpl
类的实例执行。 通过更改创建套接字实现的套接字工厂,应用程序可以将自身配置为创建适合本地防火墙的套接字。
服务器端
-
Server Socket该类实现服务器套接字。服务器套接字等待通过网络进入的请求。它根据该请求执行某些操作,然后可能将结果返回给请求者。
服务器套接字的实际工作由
SocketImpl
类的实例执行。 应用程序可以更改创建套接字实现的套接字工厂,以配置自身以创建适合本地防火墙的套接字。Client
package com.internet.TCP;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class Client1 {
public static void main(String ...args) throws IOException {
//1.创建客户端的对象(Socket)
Socket socket=new Socket("192.168.137.1",10012);
Socket s=new Socket(InetAddress.getLocalHost(),10012);
//2.监听客户端连接,返回一个Socket对象
//3.获取输出流,写数据
OutputStream os = socket.getOutputStream();
os.write("hello,你好啊".getBytes(StandardCharsets.UTF_8));
//4.释放资源
os.close();
}
}
Server
package com.internet.TCP;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server1 {
public static void main(String[] args) throws IOException {
//1.创建客户端的对象(ServerSocket)
ServerSocket serverSocket=new ServerSocket(10012);
//2.获取输入流,读数据,并把数据写到控制台
// Socket accept()侦听要连接到这个套接字并接受它
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
byte[]bytes=new byte[1024];
int len;
while((len=is.read(bytes))!=-1)
{
System.out.println( new String (bytes,0,len));
}
//字符缓冲流
/* BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line;
while((line=br.readLine())!=null)
System.out.println(line);*/
//3.释放资源
serverSocket.close();
}
}
TCP功能实践
1.服务器给出反馈
客户端代码:
package com.internet.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class Client1 {
public static void main(String[] args) throws IOException {
Socket socket=new Socket(InetAddress.getByName("192.168.137.1"),8080);
OutputStream os = socket.getOutputStream();
os.write("你好,服务器端!".getBytes(StandardCharsets.UTF_8));
InputStream is = socket.getInputStream();
byte[] bytes=new byte[1024];
int len=is.read(bytes);
System.out.println(new String(bytes,0,len));
//不需要再释放其他资源,他们都是根据socket这个对象得到的。
socket.close();
}
}
服务端代码:
package com.internet.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class Server1 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket=new ServerSocket(8080);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
byte[] bytes=new byte[1024];
int len=is.read(bytes);
System.out.println(new String (bytes,0,len));
OutputStream os = socket.getOutputStream();
os.write("我收到你信息了,客户端".getBytes(StandardCharsets.UTF_8));
serverSocket.close();
}
}
2.数据来自键盘输入
客户端:数据来自键盘录入,知道输入的数据是886,发送数据结束
服务端:接收到的数据在控制台输出
客户端:
package com.internet.test;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class Client2 {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getByName("192.168.137.1"), 8888);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = br.readLine()) != null) {
if ("886".equals(line))
break;
OutputStream os = socket.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.write(line);
bw.newLine();
bw.flush();
}
socket.close();
}
}
服务端:
package com.internet.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server2 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
3.服务端数据写入文件
客户端:客户端:数据来自键盘录入,知道输入的数据是886,发送数据结束
服务端:接收到的数据写入文本文件
客户端:
package com.internet.test;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class Client3 {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getByName("192.168.137.1"), 8889);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = br.readLine()) != null) {
if ("886".equals(line))
break;
OutputStream os = socket.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.write(line);
bw.newLine();
bw.flush();
}
socket.close();
}
}
服务端:
package com.internet.test;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server3 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8889);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("A\\test.txt")));
Socket socket = serverSocket.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
bw.flush();
}
serverSocket.close();
bw.close();
}
}
4.客户端数据来自文本文件
客户端:数据来自文本文件
服务端:接收到的数据写入文本文件
客户端:
package com.internet.test;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class Client4 {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getByName("192.168.137.1"), 8890);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("A\\test.txt")));
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
bw.flush();
}
br.close();
socket.close();
}
}
服务端:
package com.internet.test;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server4 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8890);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("A\\a.txt")));
Socket socket = serverSocket.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
bw.flush();
}
serverSocket.close();
bw.close();
}
}
5.上传文件,服务器给出反馈
客户端:数据来自文本本文件,接收服务器反馈
服务端:接受数据写入文件,给出客户端反馈
客户端:
package com.internet.test;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class Client5 {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getByName("192.168.137.1"), 9000);
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("A\\test.txt")));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
bw.flush();
}
//自定义结束标记;
// bw.write("886");
// bw.newLine();
// bw.flush();
//调用系统结束标记 public void shutdownOutput()
socket.shutdownOutput();
InputStream is = socket.getInputStream();
byte[] bytes = new byte[1024];
int len = is.read(bytes);
System.out.println(new String(bytes, 0, len));
br.close();
socket.close();
}
}
服务端:
package com.internet.test;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class Server5 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9000);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("A\\a.txt")));
Socket socket = serverSocket.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = br.readLine()) != null) {//等待读取数据,不像本机传输,网络传输有延迟,服务端不知道什么时候读完数据,需要人为加标记
// if(line.equals("886"))
// break;
bw.write(line);
bw.newLine();
bw.flush();
}
OutputStream os = socket.getOutputStream();
os.write("服务端已接受文件".getBytes(StandardCharsets.UTF_8));
bw.close();
serverSocket.close();
}
}
6.多线程实现文件上传
客户端:数据来自文本文件,接收服务器反馈
服务端:接收到的数据写入文件,给出反馈,代码用线程进行封装,为每一个客户端开启一个线程
客户端:
package com.internet.test;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class Client6 {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getByName("192.168.137.1"), 9200);
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("A\\test.txt")));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
bw.flush();
}
//自定义结束标记;
// bw.write("886");
// bw.newLine();
// bw.flush();
//调用系统结束标记 public void shutdownOutput()
socket.shutdownOutput();
InputStream is = socket.getInputStream();
byte[] bytes = new byte[1024];
int len = is.read(bytes);
System.out.println(new String(bytes, 0, len));
br.close();
socket.close();
}
}
服务端:
package com.internet.test;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server6 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9200);
while (true) {
Socket socket = serverSocket.accept();
new Thread(new ServerThread6(socket)).start();
}
}
}
服务端控制多客户:
package com.internet.test;
import java.io.*;
import java.net.Socket;
public class ServerThread6 implements Runnable {
private Socket socket;
public ServerThread6(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
//接受数据,写入文件
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int count = 0;
File file = new File("A\\a[" + count + "].txt");
while (file.exists()) {
count++;
file = new File("A\\a[" + count + "].txt");
}
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
bw.flush();
}
BufferedWriter bwServer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bwServer.write("服务端已接受文件");
bwServer.newLine();
bwServer.flush();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
URL
统一资源定位符:
定位互联网上的某一个资源
协议://IP地址:端口/项目名/资源
1.基操加应用
package com.internet.URL;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Demo1 {
public static void main(String[] args) throws IOException {
URL url = new URL("https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE4wtcK?ver=0fd1");
System.out.println(url.getProtocol());//协议
System.out.println(url.getHost());//主机IP
System.out.println(url.getPort());//端口
System.out.println(url.getPath());//文件
System.out.println(url.getFile());//全路径
System.out.println(url.getQuery());//参数
HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
InputStream is = openConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("A\\test1.jpg");
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
openConnection.disconnect();
}
}