什么是网络编程?
-
是指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接起来,在网络操作系统,网络管理软件及网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统。
网络编程的目的:
-
传播交流信息。
-
数据交换。
-
通信。
如何达到此效果?
-
需要准确的定位网络上的一台主机,例如:192.168.25.31:port(端口)
-
找到主机传输数据。
网络通信要素:
如何实现网络通讯?
-
IP
-
端口号
192.168.1.1:8080
CMD命令查询网址IP
ping www.baidu.com
端口号(0~65535)
不同的进程有不同的端口号,端口号不可冲突!用来区分软件
-
公有端口:0~1023
-
HTTP:80
-
HTTPS:443
-
FTP:21
-
Telent: 23
-
…
-
-
注册端口:1024~49151
-
Tomcat:8080
-
MySQL:3306
-
Oracle:1521
-
…
-
-
动态、私有端口:49152~65535
网络编程
InetAddress
InetAddress localIpAddress = InetAddress.getLocalHost();
System.out.println(localIpAddress); // = DESKTOP-DOPS1I8/192.168.43.50
// 通过主机ip地址或域名,ip获取ip地址对象
InetAddress byName = InetAddress.getByName("127.0.0.1");
System.out.println(byName); // = /127.0.0.1
// 通过主机名获取多个ip地址对象
InetAddress[] allByName = InetAddress.getAllByName("www.baidu.com");
Arrays.asList(allByName).stream().forEach(System.out::println); // www.baidu.com/182.61.200.6 www.baidu.com/182.61.200.7
InetAddress loopbackAddress = InetAddress.getLoopbackAddress();// 获取回环ip地址对象
System.out.println(loopbackAddress); // = localhost/127.0.0.1
/**
* 常用方法
**/
byte[] address = localIpAddress.getAddress();
System.out.println(address); // = [B@682a0b20
String canonicalHostName = localIpAddress.getCanonicalHostName(); // 规范主机名
System.out.println(canonicalHostName); // = DESKTOP-DOPS1I8
String hostAddress = localIpAddress.getHostAddress(); // 主机ip地址
System.out.println(hostAddress); // = 192.168.137.1
String hostName = localIpAddress.getHostName();// 主机名
System.out.println(hostName); // = DESKTOP-DOPS1I8
boolean reachable = localIpAddress.isReachable(3000);// 3s内是否可到达
System.out.println(reachable); // = true
InetSocketAddress
InetSocketAddress inetSocketAddress = new InetSocketAddress("xx", 80);
InetAddress address = inetSocketAddress.getAddress(); // ip地址对象
System.out.println(address); // null
String hostName = inetSocketAddress.getHostName(); // 主机名
System.out.println(hostName); // xx
String hostString = inetSocketAddress.getHostString(); // 主机字符串
System.out.println(hostString); // xx
int port = inetSocketAddress.getPort();// 端口
System.out.println(port); // 80
boolean unresolved = inetSocketAddress.isUnresolved(); // 主机名是否不能被解析为ip地址对象
System.out.println(unresolved); // true (不能解析)
通信协议
-
TCP:用户传输协议
-
连接,稳定
-
客户端、服务器
-
传输完成,释放连接,效率低
-
-
UDP:用户数据报协议
-
不连接,不稳定
-
客户端服务器:没有明确的界面
-
不管有没有准备好都可以发给你
-
导弹
-
TCP
客户端:
-
连接服务器Socket。
-
发送消息。
public static void main(String[] args) throws IOException { Socket socket = null; OutputStream os = null; try { //1.要知道服务器的地址,端口号 InetAddress server = InetAddress.getByName("127.0.0.1"); int port = 9999; socket = new Socket(server,port); //传入IP地址和端口号 os = socket.getOutputStream(); os.write("你好,我是发送者".getBytes()); } catch (IOException e) { e.printStackTrace(); }finally { socket.close(); os.close(); } }
服务器:
-
建立服务端口SeverSocket。
-
等待用户连接accept。
-
接收用户消息。
public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; Socket socket = null; InputStream is = null; ByteArrayOutputStream baos = null; try { //地址:localhost 9999 serverSocket = new ServerSocket(9999); System.out.println("server running..."); socket = serverSocket.accept(); is = socket.getInputStream();//读取客户端的消息 baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer))!=-1){ baos.write(buffer,0,len); } System.out.println(baos.toString()); } catch (IOException e) { e.printStackTrace(); }finally { baos.close(); is.close(); socket.close(); serverSocket.close(); } }
文件上传
服务器
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9000); //创建服务
Socket socket = serverSocket.accept();//阻塞式接听,会一定等待客户连接
InputStream is = socket.getInputStream(); //获取输入流
FileOutputStream fos = new FileOutputStream(new File("receive.png"));
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
OutputStream os = socket.getOutputStream(); //通知客户端接收完毕了
os.write("接收完毕".getBytes());
fos.close();
is.close();
socket.close();
serverSocket.close();
}
客户端
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);//创建一个Socket连接
OutputStream os = socket.getOutputStream(); //创建一个输出流
FileInputStream fis = new FileInputStream(new File("基础语法/src/T1.png")); //读取文件
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer))!=-1){
os.write(buffer,0,len);
}
socket.shutdownOutput(); //传输完毕
InputStream inputStream = socket.getInputStream(); //服务器接收完毕才能断开连接
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[2014];
int len2;
while ((len2=inputStream.read(bytes))!=-1){
baos.write(bytes,0,len2);
}
System.out.println(baos.toString());
fis.close();
os.close();
socket.close();
}
UDP
发短信:不用连接,需要知道对方地址
发送消息
public static void main(String[] args) throws Exception {
//建立一个socket
DatagramSocket socket = new DatagramSocket();
//键个包
String msg = "你好啊,服务器";
//发送给谁
InetAddress localhost = InetAddress.getByName("localhost");
int port = 9090;
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
//发送包
socket.send(packet);
socket.close();
}
接收段
public static void main(String[] args) throws Exception {
//开放端口
DatagramSocket socket = new DatagramSocket(9090);
//接收数据包
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
//阻塞接收
socket.receive(packet);
System.out.println(packet.getAddress().getHostAddress()); // = 127.0.0.1
System.out.println(new String(packet.getData(),0,packet.getLength())); // = 你好啊,服务器
socket.close();
}
循环发送
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(8888);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //准备数据控制台读取System.in
while (true){
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6667));
socket.send(packet);
if (data.equals("bye")){
break;
}
}
socket.close()
}
接收
public static void main(String[] args) throws Exception{
DatagramSocket socket = new DatagramSocket(6667);
while (true){
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container,0,container.length);
socket.receive(packet);
byte[] data = packet.getData();
String receiveData = new String(data,0,data.length);
System.out.println(receiveData);
if (receiveData.equals("bye")){
break;
}
}
socket.close();
}
双方同时接收
public class TalkReceive implements Runnable{
DatagramSocket socket = null;
private int port;
private String msgFrom;
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];
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);//阻塞式接收包裹
socket.receive(packet);
//断开连接
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(msgFrom+":"+receiveData);
if (receiveData.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
public class TalkSend implements Runnable{
DatagramSocket socket = null;
BufferedReader reader = null;
private int fromPort;
private String toIP;
private int toPort;
public TalkSend(int fromPort, String toIP, int toPort) {
this.fromPort = fromPort;
this.toIP = toIP;
this.toPort = toPort;
try {
socket = new DatagramSocket(fromPort);
//准备数据 从控制台读取
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort));
socket.send(packet);
if (data.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
首先开始老师线程
public class TalkTeacher {
public static void main(String[] args) {
//开启两个线程
new Thread(new TalkSend(6661,"localhost",8881)).start();
new Thread(new TalkReceive(9992,"学生")).start();
}
}
然后开启学生线程
public class TalkStudent {
public static void main(String[] args) {
//开启两个线程
new Thread(new TalkSend(7777,"localhost",9992)).start();
new Thread(new TalkReceive(8881,"老师")).start();
}
}
URL
统一资源定位符:定位资源的,定位互联网上的某一资源
DNS 域名解析 www.baidu.com
协议:// ip 地址 : 端口 / 项目名/资源
import java.net.URL;
public static void main(String[] args) throws Exception {
URL url = new URL("http://localhost:8080/hello/index.jsp?username=zr&password=88");
System.out.println(url.getProtocol()); //协议 = http
System.out.println(url.getHost()); //主机IP = localhost
System.out.println(url.getPort()); //端口 = 8080
System.out.println(url.getPath()); //文件 = /hello/index.jsp
System.out.println(url.getFile()); //全路径 = /hello/index.jsp?username=zr&password=88
System.out.println(url.getQuery()); //参数 = username=zr&password=88
}
下载网络资源
public static void main(String[] args) throws IOException {
URL url = new URL("http://localhost:8080/guanxin/Theguan.png"); //资源地址
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream(); //连接得到这个资源
FileOutputStream fos = new FileOutputStream("基础语法/src/guan.png");
byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
fos.write(buffer,0, len); //写出数据
}
//断开连接
fos.close();
is.close();
urlConnection.disconnect();
}
破茧
URL url = new URL("https://ws.stream.qqmusic.qq.com/C400003kSb8X2Ie1Ue.m4a?guid=435264108&vkey=D5D47FCEDC99D48B2C242AB949F2E59EA91478AC83CD892AEDD5F26D0D59E6A09A203B60628F4F69EC16EBB470CC3B6D22137FE893103726&uin=1064936282&fromtag=66");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("基础语法/src/pojian.m4a");
byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
fos.write(buffer,0, len);//写出数据
}
fos.close();
is.close();
urlConnection.disconnect();
4万+

被折叠的 条评论
为什么被折叠?



