网络编程学习
网络编程
1.1 、IP
import java.net.InetAddress;
import java.net.UnknownHostException;
//测试IP
public class TestInetAddress {
public static void main(String[] args) {
//查询本机地址
try {
InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
System.out.println(inetAddress);
InetAddress inetAddress1 = InetAddress.getByName("localhost");
System.out.println(inetAddress1);
InetAddress inetAddress2 = InetAddress.getLocalHost();
System.out.println(inetAddress2);
//查询网站IP地址
InetAddress inetAddress3 = InetAddress.getByName("www.baidu.com");
System.out.println(inetAddress3);
//常用方法
System.out.println(inetAddress3.getAddress());
System.out.println(inetAddress3.getCanonicalHostName());//规范的名字
System.out.println(inetAddress3.getHostAddress());//ip
System.out.println(inetAddress3.getHostName());//域名,或者自己电脑的名字
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
1.2、端口
端口表示计算机上的一个程序的进程
-
不同的进程有不同的端口号!用来区分软件
-
被规定的端口号是0~65535
-
TCP、UDP:65535*2 单个协议下端口号不能冲突
-
端口分类
-
公有端口 0~1023
-
HTTP:80
- HTTPS:443
-
FTP:21
-
Telent:23
-
-
程序注册端口: 1024~49151,分配用户或者程序
-
Tomcat:8080
-
MySQL:3306
-
Oracle:1521
-
动态、私有:49152~65535
netstat -ano #查看所有端口 netstat -ano|findstr "端口号" #查看指定端口 tasklist|findstr "端口号" #查看指定端口的进程import java.net.InetSocketAddress; public class TestInetSocketAddress { public static void main(String[] args) { InetSocketAddress socketAddress1 = new InetSocketAddress("localhost",8080); InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",8080); System.out.println(socketAddress); System.out.println(socketAddress1); System.out.println(socketAddress.getAddress()); System.out.println(socketAddress.getHostName());//地址 System.out.println(socketAddress.getPort());/端口 } }
-
1.3、TCP通信
1.3.1、客户端
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
//客户端
public class TcpClientDemon1 {
public static void main(String[] args) {
InetAddress serverIP = null;
Socket socket = null;
OutputStream os = null;
try {
//1.获取服务器端的IP和端口号
serverIP = InetAddress.getByName("127.0.0.1");
int Port = 9999;
//2.创建一个socket连接
socket = new Socket(serverIP,Port);
//3.发送消息的 IO流
os = socket.getOutputStream();
os.write("你好:欢迎学习狂神说java!!!".getBytes());
} catch (Exception 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();
}
}
}
}
}
1.3.2、服务器端
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
//服务器
public class TcpServerDemon1 {
public static void main(String[] args) {
ServerSocket serverSocket =null;
Socket socket =null;
InputStream is = null;
ByteArrayOutputStream bs = null;
try {
//1.我的一个地址
serverSocket = new ServerSocket(9999);
//2.等待客户端连接过来
socket = serverSocket.accept();
//3.读取客户端发过来的消息
is = socket.getInputStream();
//管道流
bs = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
bs.write(buffer,0,len);
}
System.out.println(bs.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
if(bs!=null){
try {
bs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!=null){
try {
is.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();
}
}
}
}
}
1.3.3、客户端(下载)
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
//客户端
public class TcpClientDemon2 {
public static void main(String[] args) throws Exception{
//1.创建一个Socket连接
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
//2.创建一个输出流
OutputStream os = socket.getOutputStream();
//3.读取文件
FileInputStream fis = new FileInputStream(new File("1.jpg"));
//4.写出文件
byte[] buffer = new byte[1024];
int len;
while((len=fis.read(buffer))!=-1){
os.write(buffer,0,len);
}
socket.shutdownOutput();//通知服务器端,我已经完成看输出。
//确定服务器接收完毕,断开连接
InputStream is = socket.getInputStream();
ByteArrayOutputStream bso = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len1;
while((len1=is.read(bytes))!=-1){
bso.write(bytes,0,len1);
}
System.out.println(bso.toString());
//5.关闭资源
bso.close();
is.close();
os.close();
fis.close();
socket.close();
}
}
1.3.4、服务器端(下载)
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
//服务器
public class TcpServerDemon2 {
public static void main(String[] args) throws Exception {
//1.创建服务
ServerSocket serverSocket = new ServerSocket(9000);
//2.创建客户端的监听连接
Socket socket =serverSocket.accept();//阻塞式监听
//3.获取输入流
InputStream is = socket.getInputStream();
//4.文件输出
FileOutputStream fio = new FileOutputStream(new File("2.jpg"));
byte[] buffer = new byte[1024];
int len;
while((len=is.read(buffer))!=-1){
fio.write(buffer,0,len);
}
OutputStream os = socket.getOutputStream();
os.write("我接受完毕了".getBytes());
//5.关闭资源
os.close();
fio.close();
is.close();
socket.close();
serverSocket.close();
}
}
1.4、UDP通信
1.4.1、发送端
package 寒假训练.狂神.Demon网络编程.UDP通信;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpClientDemon1 {
public static void main(String[] args) throws Exception {
//1.建立一个socket
DatagramSocket socket = new DatagramSocket();
//创建键盘输入
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int port = 9000;
String s = "bye";
while(true){
//2.创建一个包
String str = reader.readLine();
//数据发给谁
DatagramPacket packet = new DatagramPacket(str.getBytes(),0,
str.getBytes().length,InetAddress.getByName("localhost"),port);
//3.发送包
socket.send(packet);
if (str.equals(s)){
break;
}
}
//4.关闭连接
socket.close();
}
}
1.4.2、接收端
package 寒假训练.狂神.Demon网络编程.UDP通信;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPServerDemon1 {
public static void main(String[] args) throws Exception {
//开放端口
DatagramSocket socket = new DatagramSocket(9000);
String s = "bye";
while (true){
//接受数据
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);//阻塞接收
byte[] data =packet.getData();
//加上.trim()是为了去除空格
String str = new String(data,0,data.length).trim();
System.out.println(str);
if (str.equals(s)){
break;
}
}
//关闭连接
socket.close();
}
}
1.4.3、老师与学生通信,利用udp和多线程
- 学生
package 寒假训练.狂神.Demon网络编程.UDP通信.多线程;
public class Student {
public static void main(String[] args) {
new Thread(new UdpSend(8000,"localhost",9999)).start();
new Thread(new UdpAccept(8888,"老师")).start();
}
}
- 老师
package 寒假训练.狂神.Demon网络编程.UDP通信.多线程;
public class Teacher {
public static void main(String[] args) {
new Thread(new UdpSend(5555,"localhost",8888)).start();
new Thread(new UdpAccept(9999,"学生")).start();
}
}
- 发送端
package 寒假训练.狂神.Demon网络编程.UDP通信.多线程;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
//发送
public class UdpSend implements Runnable {
DatagramSocket socket = null;
BufferedReader reader = null;
private int fromPort;//从哪个端口出去
private String toIP;
private int toPort;
public UdpSend(int fromPort,String toIP, int toPort) {
this.fromPort = fromPort;
this.toIP = toIP;
this.toPort = toPort;
try {
//1.建立一个socket、创建键盘输入
socket = new DatagramSocket(fromPort);
reader = new BufferedReader(new InputStreamReader(System.in));
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void run() {
while(true){
//2.创建一个包
try {
String str = reader.readLine();
//数据发给谁
DatagramPacket packet = new DatagramPacket(str.getBytes(),0,
str.getBytes().length, new InetSocketAddress(this.toIP,this.toPort));
//3.发送包
socket.send(packet);
if (str.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
//4.关闭连接
socket.close();
}
}
- 接收端
package 寒假训练.狂神.Demon网络编程.UDP通信.多线程;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
//接受
public class UdpAccept implements Runnable {
DatagramSocket socket = null;
private int port1;
private String msgfrom;
public UdpAccept(int port1,String msgfrom) {
this.port1 = port1;
this.msgfrom = msgfrom;
try {
//开放端口
socket = new DatagramSocket(port1);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
try {
//接受数据
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);//阻塞接收
byte[] data =packet.getData();
//加上.trim()是为了去除空格
String str = new String(data,0,data.length).trim();
System.out.println(msgfrom+":"+str);
if (str.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭连接
socket.close();
}
}
本文详细介绍了网络编程的基础,包括IP地址的获取,端口的作用及其分类,TCP通信的客户端与服务器端实现,以及UDP通信的发送与接收示例,还涉及老师与学生间的多线程UDP通信教学实践。
936





