java基础之网络编程
1.1网络编程中的两个主要问题:
-
如何准确定位网络中的一台主机
-
主机之间如何通信
1.2网络中的主要元素
- IP地址,端口号port,套接字socket
- 主要的通信协议tcp,udp
IP 地址:InetAddress
-
唯一定位一台网络主机
-
127.0.0.1:localhost表示本台主机
-
IP地址分类
-
IPV4:由网络号+主机号组成,共有4个字节,32位,42亿~,30亿在北美,4亿在亚洲,2011年已用尽。
分类 网络号+主机号 最多可分配主机数 最大分配网络数 最小网络号 最大网络号 A类 (第一位是0)1+3 2的7次方 - 2 1 126 B类 (前两位10)2+2 2的12次方-2 128.1 191.255 C类 (前三位110)3+1 2的17次方-2 192.0.1 223.255.255 D类 前四位是1110,多播地址 E类 前四位1111,保留位今后使用
-
-
IPV6:128位,8个无符号整数
端口号port:表示应用进程 的标识符,唯一表示进程
- 规定为0~65535
- 单个协议下端口号不能冲突
- 分类:
- 公有端口0-1023
- http:80
- https:443
- ftp:21
- telent(远程控制):23
- 程序注册端口:1024-49151,由用户或程序分配
- Tomcat:8080
- MySQL:3306
- Oracle:1521
- 动态,私有:49152-65535
- netstat -ano查看所有端口
socket套接字:IP地址:端口号
1.3 tcp和udp比较
-
tcp传输控制协议:首部最小20字节
- 面向连接的:必须实现建立连接
- 提供可靠交付
- 提供全双工通信
- 只提供一对一通信
- 面向字节流
-
udp用户数据报协议:首部只有8字节
-
面向无连接的:不需要事先建立连接
-
尽最大努力交付:不可靠交付
-
无拥塞控制:适合多媒体通信
-
支持多种通信方式:一对多,多对多,一对一,多对一
-
面向报文
-
三次握手,四次挥手
tcp编程
- 客户端
public class Client06 {
public static void main(String[] args) {
{
OutputStream os = null;
Socket socket = null;
InetAddress net;
//InputStream in=null;
ByteArrayOutputStream bos=null;
try {
//设置IP地址和对方的端口号
net = InetAddress.getByName("127.0.0.1");
int port = 9000;
try {
socket = new Socket(net, port);
os = socket.getOutputStream();
os.write("王琴在学习Java".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
- 服务端
public class Server06 {s
public static void main(String[] args) {
{
ServerSocket serverSocket=null;
Socket socket=null;
InputStream in=null;
OutputStream ops=null;
ByteArrayOutputStream os=null;
try {
serverSocket = new ServerSocket(9000);
while (true) {
socket = serverSocket.accept();
in = socket.getInputStream();
os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
os.write(buffer,0,len);
}
System.out.println(os.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(ops!=null){
try {
ops.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
udp编程
public class sender {
public static void main(String[] args) throws Exception {
//建立socket
DatagramSocket socket=new DatagramSocket();
//打包包裹
String msg=new String("发送包裹");
InetAddress ip=InetAddress.getByName("localhost");
DatagramPacket packet=new DatagramPacket(msg.getBytes(StandardCharsets.UTF_8),0,msg.getBytes().length,ip,9999);
//发送包裹
socket.send(packet);
socket.close();
}
}
public class receiver {
public static void main(String[] args) throws Exception {
DatagramSocket socket=new DatagramSocket(9999);
//打包包裹
byte[]buffer=new byte[1024];
DatagramPacket packet=new DatagramPacket(buffer,0,buffer.length);
//发送包裹
socket.receive(packet);
System.out.println(new String(packet.getData(),0,packet.g etLength()));
socket.close();
}
聊天实现
public class sender implements Runnable{
DatagramSocket socket=null;
DatagramPacket packet=null;
BufferedReader msg=null;
private int fromPort;
private int toPort;
private String toIP;
public sender( int fromPort,int toPort, String toIP) throws SocketException {
this.toPort = toPort;
this.fromPort = fromPort;
this.toIP = toIP;
socket=new DatagramSocket(fromPort);
msg= new BufferedReader(new InputStreamReader(System.in));
}
@Override
public void run() {
while (true) {
String data=null;
try {
data=msg.readLine();
packet= new DatagramPacket(data.getBytes(),
0, data.length(),
new InetSocketAddress(this.toIP, this.toPort));
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
if(data.equals("bye")){
break;
}
}
socket.close();
}
}
public class receiver implements Runnable{
DatagramSocket socket=null;
private int port;
private String msgfrom;
public receiver(int port,String msgfrom) throws SocketException {
this.port = port;
this.msgfrom=msgfrom;
socket=new DatagramSocket(port);
}
@Override
public void run() {
try {
while(true) {
byte[] bf = new byte[1024];
DatagramPacket packet = new DatagramPacket(bf, 0, bf.length);
socket.receive(packet);
byte[] data=packet.getData();
String datas=new String(data,0,data.length);
System.out.println(msgfrom+":"+datas);
if(datas.equals("bye")){
break;
}
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
socket.close();
}
}
创建两个聊天
public class student {
public static void main(String[] args) throws SocketException {
new Thread(new sender(9999,8888,"localhost")).start();
new Thread(new receiver(7777,"老师")).start();
}
}
public class teacher {
public static void main(String[] args) throws SocketException {
new Thread(new sender(6666,7777,"localhost")).start();
new Thread(new receiver(8888,"学生")).start();
}
}
爬取网络资源
public class urlResource {
public static void main(String[] args) {
try {
//下载资源
URL url=new URL("https://dl.stream.qqmusic.qq.com/RS020606uEws3PNkhT.mp3");
//连接资源
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
File file=new File("D:\\vip资源\\t.mp3");
FileOutputStream fos=new FileOutputStream(file);
InputStream in=connection.getInputStream();
byte[]bf=new byte[1024];
int len;
while ((len=in.read(bf))!=-1){
fos.write(bf,0,len);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)