网络编程实战讲解
Posted (x²+y²-1)³=x²y³
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了网络编程实战讲解相关的知识,希望对你有一定的参考价值。
网络编程实战讲解
TCP实现聊天
客户端
package com.example.quickstart;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
//客户端
public class TCPClient {
public static void main(String[] args) {
Socket socket=null;
OutputStream outputStream=null;
try {
//要知道服务器的地址
InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
int port=8888;//端口号
//创建一个socket连接
socket = new Socket(inetAddress, port);
//发送消息 IO流
outputStream = socket.getOutputStream();
outputStream.write("你好,欢迎来到我的世界".getBytes());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务器端
package com.example.quickstart;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) {
ServerSocket serverSocket=null;
Socket accept=null;
InputStream inputStream=null;
ByteArrayOutputStream arrayOutputStream=null;
//我得有一个地址
try {
serverSocket = new ServerSocket(8888);
while(true){
//等待客户端连接过来
accept = serverSocket.accept();
//读取客户端的消息
inputStream = accept.getInputStream();
//管道流
arrayOutputStream = new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len;
while((len=inputStream.read(buffer))!=-1){
arrayOutputStream.write(buffer,0,len);
}
System.out.println(arrayOutputStream.toString());
}
/*byte[] bytes = new byte[1024];//1k
int len;
while((len=inputStream.read(bytes))!=-1){
String message = new String(bytes, 0, len);
System.out.println(message);
}*/
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
arrayOutputStream.close();
inputStream.close();
accept.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
TCP文件上传实现
客户端
package com.example.quickstart;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TCPUploadClient {
public static void main(String[] args) {
try {
//创建一个Socket连接
Socket socket = new Socket(InetAddress.getByName("localhost"), 9000);
//创建一个输出流
OutputStream outputStream = socket.getOutputStream();
//文件输入流-读取文件
FileInputStream inputStream = new FileInputStream(new File("img1.webp"));
//写出文件
byte[] buffer=new byte[1024];
int len;
while((len=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,len);
}
//通知服务器我已经结束了
socket.shutdownOutput();
//确定服务器接收完毕,才能断开连接
InputStream socketInputStream = socket.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer2 = new byte[2048];
int len2;
while((len2=socketInputStream.read(buffer2))!=-1){
byteArrayOutputStream.write(buffer2,0,len2);
}
String message = byteArrayOutputStream.toString();
System.out.println(message);
//关闭资源
byteArrayOutputStream.close();
socketInputStream.close();
inputStream.close();
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器端
package com.example.quickstart;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPUploadServer {
public static void main(String[] args) {
try {
//创建服务
ServerSocket serverSocket = new ServerSocket(9000);
//监听客户端的连接
Socket accept = serverSocket.accept();//阻塞式监听,会一直等待客户端连接
//获取输入流
InputStream inputStream = accept.getInputStream();
//文件输出
FileOutputStream outputStream = new FileOutputStream(new File("receive.webp"));
byte[] buffer = new byte[1024];
int len;
while((len=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,len);
}
//通知客户端我接收完毕了
OutputStream acceptOutputStream = accept.getOutputStream();
acceptOutputStream.write("我接收完毕了,你可以断开了".getBytes());
//关闭资源
outputStream.close();
inputStream.close();
accept.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UDP消息发送
客户端
package com.example.udp;
import java.io.IOException;
import java.net.*;
//不需要连接服务器
public class UDPClientDemo1 {
public static void main(String[] args) {
try {
//建立一个Socket
DatagramSocket socket = new DatagramSocket();
//建个包
String message="你好,服务器";
byte[] messageBytes = message.getBytes();
InetAddress localhost = InetAddress.getByName("localhost");//发送给谁
int port = 9090;//端口号
DatagramPacket packet = new DatagramPacket(messageBytes,0,messageBytes.length,localhost,port);
//发送包
socket.send(packet);
//关闭流
socket.close();
} catch (SocketException | UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器端
package com.example.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
//还是要等待客户端的连接
public class UDPServerDemo1 {
public static void main(String[] args) {
try {
//开放端口
DatagramSocket socket = new DatagramSocket(9090);
//接收数据包
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);//阻塞接收
//输出包裹信息
System.out.println(new String(packet.getData()));
//关闭连接
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UDP连续发送消息
发送方
package com.example.udp;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public class UDPSenderDemo1 {
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket(8888);
//准备数据:控制台读取 System.in
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while(true){
String message = reader.readLine();
byte[] messageBytes = message.getBytes();
InetAddress localhost = InetAddress.getByName("localhost");
DatagramPacket packet = new DatagramPacket(messageBytes, 0, messageBytes.length, localhost, 6666);
socket.send(packet);
if("bye".equalsIgnoreCase(message)){
break;
}
}
socket.close();
} catch (SocketException | UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
接收方
package com.example.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UDPReceiveDemo1 {
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket(6666);
while(true){
//准备接收包裹
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);
byte[] data = packet.getData();
String message = new String(data, 0, data.length);
System.out.println(message);
if("bye".equalsIgnoreCase(message)){
break;
}
}
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UDP多线程在线咨询
发送方
package com.example.udp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public class ChatSender implements Runnable {
DatagramSocket socket=null;
BufferedReader reader=null;
private String toIP;
private int toPort;
private int fromPort;
public ChatSender(String toIP, int toPort, int fromPort) {
this.toIP = toIP;
this.toPort = toPort;
this.fromPort = fromPort;
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[] dataBytes = data.getBytes();
DatagramPacket packet = new DatagramPacket(dataBytes, 0, dataBytes.length, new InetSocketAddress(toIP, toPort));
socket.send(packet);
if("bye".equalsIgnoreCase(data)){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
接收方
package com.example.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class ChatReceiver implements Runnable {
DatagramSocket socket=null;
private int port;
public ChatReceiver(int port) {
this.port = port;
try {
socket=new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
byte[] buffer=null;
DatagramPacket packet=null;
while(true){
try {
buffer=new byte[1024];
packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);
byte[] data = packet.getData();
String message = new String(data);
System.out.println("fromIP: "+packet.getAddress()+", fromMessage: "+message);
if("bye".equalsIgnoreCase(message)){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
学生:即是发送方也是接收方
package com.example.udp;
public class ChatStudent {
public static void main(String[] args) {
//开启两个线程
new Thread(new ChatSender("localhost",6666,7777)).start();
new Thread(new ChatReceiver(8888)).start();
}
}
老师:即是发送方也是接收方
package com.example.udp;
public class ChatTeacher {
public static void main(String[] args) {
new Thread(new ChatSender("localhost",8888,9999)).start();
new Thread(new ChatReceiver(6666)).start();
}
}
URL下载网络资源
爬取网易云音乐
package com.example.url;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
//下载地址:http://localhost:8080/favicon.ico
//ps:需打开tomcat
public class URLDownload {
public static void main(String[] args) {
try {
//下载地址
URL url = new URL("https://m801.music.126.net/20211003095941/a0a7f59871fb88d6492845ca20aac658/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/11062312467/6a10/8c90/0eaf/e12ae5442e789a1e2215ddeae103befb.m4a");
//连接到这个资源
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("奔流.m4a");
byte[] buffer = new byte[1024];
int len;
while((len=inputStream.read(buffer))!=-1){
fileOutputStream.write(buffer,0,len);
}
fileOutputStream.close();
inputStream.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!
以上是关于网络编程实战讲解的主要内容,如果未能解决你的问题,请参考以下文章