网络编程:就是用来实现网络互连的不同计算机上运行的程序间可以进行数据交换
网络编程三要素: IP地址、端口、协议;
Socket套接字概述:
网络上具有唯一标识的IP地址和端口号组合在一起才能构成唯一能识别的标识符套接字。(Socket=IP+端口号)
Socket原理机制:
InetAddress类的概述
为了方便我们对IP地址的获取和操作,java提供了一个类InetAddress 供我们使用
InetAddress类的常见功能
1.public static InetAddress getByName(String host)//通过主机名获取IP地址
2. public String getHostAddress()//获取IP
3.public String getHostName()//获取主机名
4.getLocalHost();
代码演示
public class test {
public static void main(String[] args) throws UnknownHostException {
String s = InetAddress.getLocalHost().getHostAddress();//当不知道主机名时调用的方法,获取IP地址
String hostName = InetAddress.getLocalHost().getHostName();//当不知道主机名时调用的方法,获取主机名
System.out.println("地址是:"+s);
System.out.println("主机名:"+hostName);
String s1 = InetAddress.getByName("WIN-3A060ANE527").getHostAddress();//通过主机名获取IP地址
System.out.println(s1);
}
}
格式:
UDP网络编程
Java针对UDP提供的Socket(DatagramSocket用来发送和接收数据报包)
客户端
1.创建套接字
DatagramSocket ds = new DatagramSocket();
2.发送:对方的IP,端口
数据报包:DatagramPacket d= new DatagramPacket();
Ds.send(d);
3.释放资源
Ds.close();
服务端
1.暴露端口,建立服务端套接字
DattagramSocket d=new DattagramSocket(端口号);
2.接受数据
byte[] bytes = new byte[1024];
创建空的数据接收报包DatagramPacket d1= new DatagramPacket(bytes,bytes.length);
d.receive(d1);
d1.getData()//获取数据
d1.getLength()//获取实际数据长度
释放资源
d.close();
代码演示:
服务类:
public class Server {
public static void main(String[] args) throws IOException {
//暴露端口号
DatagramSocket socket = new DatagramSocket(9999);
//创建空的数据报包
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
System.out.println("服务器已打开,等待数据......");
//接收数据
socket.receive(packet);//阻塞方法
//获得数据
String s = new String(packet.getData(), 0, packet.getLength());
System.out.println(s);
// byte[] data = packet.getData();//获取数据
// int length = packet.getLength();//获取实际长度
}
}
用户类:
public class Client {
public static void main(String[] args) throws IOException {
//创建套接字
DatagramSocket socket = new DatagramSocket();
//创建数据报包
byte[] bytes = "准备睡觉呀,啦啦啦".getBytes();
DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 9999);
//发送
socket.send(packet);
//关闭
socket.close();
}
}
服务类实现:
public class Server {
public static void main(String[] args) throws IOException {
//暴露端口号
DatagramSocket socket = new DatagramSocket(9999);
System.out.println("服务器已打开,等待数据......");
while(true){
//创建空的数据报包
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
//接收数据
socket.receive(packet);//阻塞方法
//获得数据
String s = new String(packet.getData(), 0, packet.getLength());
if(s.equals("886")){
break;
}
System.out.println(s);
}
socket.close();
// byte[] data = packet.getData();//获取数据
// int length = packet.getLength();//获取实际长度
}
}
用户类实现:
public class Client {
public static void main(String[] args) throws IOException {
//创建套接字
DatagramSocket socket = new DatagramSocket();
while (true){
System.out.println("请输入数据:886代表退出");
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
//创建数据报包
byte[] bytes = s.getBytes();
DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 9999);
//发送
socket.send(packet);
if(s.equals("886")){
break;
}
}
//关闭
socket.close();
}
}
用户类
public class Client extends Thread{
@Override
public void run() {
try {
new Thread(){
@Override
public void run() {
try {
DatagramSocket socket = new DatagramSocket(7777);
//创建空的数据报包
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
//接收数据
socket.receive(packet);//阻塞方法
//获得数据
String s = new String(packet.getData(), 0, packet.getLength());
System.out.println("A接收到B的消息:"+s);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
//创建套接字
DatagramSocket socket = new DatagramSocket();
System.out.println("A发送信息:");
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
//创建数据报包
byte[] bytes = s.getBytes();
DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 9999);
//发送
socket.send(packet);
//关闭
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务类
public class Server extends Thread {
@Override
public void run() {
new Thread() {
@Override
public void run() {
try {
//暴露端口号
DatagramSocket socket = new DatagramSocket(9999);
//创建空的数据报包
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
//接收数据
socket.receive(packet);//阻塞方法
//获得数据
String s = new String(packet.getData(), 0, packet.getLength());
System.out.println("B接收到A的信息:"+s);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
// byte[] data = packet.getData();//获取数据
// int length = packet.getLength();//获取实际长度
}
}.start();
try {
//创建套接字
DatagramSocket socket = new DatagramSocket();
System.out.println("B发送信息:");
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
//创建数据报包
byte[] bytes = s.getBytes();
DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 7777);
//发送
socket.send(packet);
//关闭
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#### Client类实现
package practice;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class Client extends Thread{
studen stu;
public Client(studen studen) {
this.stu=studen;
}
@Override
public void run() {
while(true){
synchronized (stu){
if(stu.flag){
try {
stu.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
new Thread(){
@Override
public void run() {
try {
DatagramSocket socket = new DatagramSocket(7777);
//创建空的数据报包
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
//接收数据
socket.receive(packet);//阻塞方法
//获得数据
String s = new String(packet.getData(), 0, packet.getLength());
System.out.println("A接收到B的消息:"+s);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
//创建套接字
DatagramSocket socket = new DatagramSocket();
System.out.println("A发送信息:");
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
//创建数据报包
byte[] bytes = s.getBytes();
DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 9999);
//发送
socket.send(packet);
//关闭
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
stu.flag=true;
stu.notify();
}
}
}
}
#### Server类实现
package practice;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class Server extends Thread {
studen stu;
public Server(studen studen) {
this.stu=studen;
}
@Override
public void run() {
while(true){
synchronized (stu){
new Thread() {
@Override
public void run() {
try {
//暴露端口号
DatagramSocket socket = new DatagramSocket(9999);
//创建空的数据报包
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
//接收数据
socket.receive(packet);//阻塞方法
//获得数据
String s = new String(packet.getData(), 0, packet.getLength());
System.out.println("B接收到A的信息:"+s);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
// byte[] data = packet.getData();//获取数据
// int length = packet.getLength();//获取实际长度
}
}.start();
if(!stu.flag){
try {
stu.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
//创建套接字
DatagramSocket socket = new DatagramSocket();
System.out.println("B发送信息:");
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
//创建数据报包
byte[] bytes = s.getBytes();
DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 7777);
//发送
socket.send(packet);
//关闭
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
stu.flag=false;
stu.notify();
}
}
}
}
#### 标记声明
public class studen {
public static boolean flag=false;
}
格式:
客户端
服务端
代码实现:
用户类实现:
public class Client {
public static void main(String[] args) throws IOException {
//创建套接字
Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
//发送消息
OutputStream stream = socket.getOutputStream();
stream.write("今天,真凉快呀".getBytes());
//释放资源
stream.close();
}
}
服务类实现:
public class Server {
public static void main(String[] args) throws IOException {
//建立套接字,暴露端口
ServerSocket socket = new ServerSocket(8888);
//监听
System.out.println("服务器一打开,等待数据传输......");
Socket ac = socket.accept();
//读取消息,并打印
InputStream inputStream = ac.getInputStream();
byte[] bytes = new byte[1024];
int read = inputStream.read(bytes);
String s = new String(bytes, 0, read);
System.out.println(s);
}
}
用户类实现:
public class Client {
public static void main(String[] args) throws IOException {
//创建套接字
Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
//发送消息
OutputStream stream = socket.getOutputStream();
Scanner scanner = new Scanner(System.in);
while (true){
System.out.println("请输入数据:");
String s = scanner.nextLine();
stream.write(s.getBytes());
if(s.equals("886")){
break;
}
}
socket.shutdownOutput();
//释放资源
stream.close();
}
服务类实现:
public class Server {
public static void main(String[] args) throws IOException {
//建立套接字,暴露端口
ServerSocket socket = new ServerSocket(8888);
//监听
System.out.println("服务器一打开,等待数据传输......");
Socket ac = socket.accept();
//读取消息,并打印
InputStream inputStream = ac.getInputStream();
while(true){
byte[] bytes = new byte[1024];
int read = inputStream.read(bytes);
String s = new String(bytes, 0, read);
if(s.equals("886")){
break;
}
System.out.println(s);
}
}
}
用户类:
public class Client {
public static void main(String[] args) throws IOException {
//创建套接字
Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
//发送消息
OutputStream stream = socket.getOutputStream();
Scanner scanner = new Scanner(System.in);
while (true){
System.out.println("请输入数据:");
String s = scanner.nextLine();
stream.write(s.getBytes());
stream.write("\t \n".getBytes());
if(s.equals("886")){
break;
}
}
socket.shutdownOutput();
//释放资源
stream.close();
}
}
服务类:
public class Server {
public static void main(String[] args) throws IOException {
//建立套接字,暴露端口
ServerSocket socket = new ServerSocket(8888);
//监听
System.out.println("服务器一打开,等待数据传输......");
Socket ac = socket.accept();
//读取消息,并存入文件
InputStream inputStream = ac.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
BufferedWriter writer = new BufferedWriter(new FileWriter("haha.txt"));
String s = null;
while ((s=reader.readLine())!=null){
writer.write(s);
writer.newLine();
writer.flush();
}
System.out.println("存入成功");
reader.close();
writer.close();
}
}
用户类:
public class Client {
public static void main(String[] args) throws IOException {
//创建套接字
Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
//读取文件,发送消息
OutputStream stream = socket.getOutputStream();
BufferedReader reader = new BufferedReader(new FileReader("haha.txt"));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream));
String s=null;
while ((s=reader.readLine())!=null){
writer.write(s);
writer.newLine();
writer.flush();
}
socket.shutdownOutput();
//释放资源
stream.close();
}
}
服务类:
public class Server {
public static void main(String[] args) throws IOException {
//建立套接字,暴露端口
ServerSocket socket = new ServerSocket(8888);
//监听
System.out.println("服务器一打开,等待数据传输......");
Socket ac = socket.accept();
//读取消息,并打印
InputStream inputStream = ac.getInputStream();
BufferedReader bfr = new BufferedReader(new InputStreamReader(inputStream));
String line=null;
while((line=bfr.readLine())!=null){
System.out.println(line);
}
System.out.println("打印完毕");
}
}
用户类:
public class Client {
public static void main(String[] args) throws IOException {
//创建套接字
Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
//读取文件,发送消息
OutputStream stream = socket.getOutputStream();
BufferedReader reader = new BufferedReader(new FileReader("haha.txt"));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream));
String s=null;
while ((s=reader.readLine())!=null){
writer.write(s);
writer.newLine();
writer.flush();
}
socket.shutdownOutput();
//释放资源
stream.close();
}
}
服务类:
public class Server {
public static void main(String[] args) throws IOException {
//建立套接字,暴露端口
ServerSocket socket = new ServerSocket(8888);
//监听
System.out.println("服务器一打开,等待数据传输......");
Socket ac = socket.accept();
//读取消息,并存入文件
InputStream inputStream = ac.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
BufferedWriter writer = new BufferedWriter(new FileWriter("haha1.txt"));
String s = null;
while ((s=reader.readLine())!=null){
writer.write(s);
writer.newLine();
writer.flush();
}
System.out.println("存入成功");
reader.close();
writer.close();
}
}
用户类:
public class Client {
public static void main(String[] args) throws IOException {
//创建套接字
Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
//读取文件,发送消息
OutputStream stream = socket.getOutputStream();
BufferedReader reader = new BufferedReader(new FileReader("haha.txt"));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream));
String s=null;
while ((s=reader.readLine())!=null){
writer.write(s);
writer.newLine();
writer.flush();
}
socket.shutdownOutput();
InputStream stream1 = socket.getInputStream();
byte[] bytes = new byte[1024];
int read = stream1.read(bytes); //返回值为实际长度
String s1 = new String(bytes, 0, read);
System.out.println(s1);
//释放资源
stream.close();
stream1.close();
socket.close();
}
服务类:
public class Server {
public static void main(String[] args) throws IOException {
//建立套接字,暴露端口
ServerSocket socket = new ServerSocket(8888);
//监听
System.out.println("服务器一打开,等待数据传输......");
Socket ac = socket.accept();
//读取消息,并存入文件
InputStream inputStream = ac.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
BufferedWriter writer = new BufferedWriter(new FileWriter("haha11.txt"));
String s = null;
while ((s=reader.readLine())!=null){
writer.write(s);
writer.newLine();
writer.flush();
}
OutputStream stream = ac.getOutputStream();
stream.write("文件已收到哦。".getBytes());
stream.close();
reader.close();
writer.close();
}
}
用户类:
public class Clicent {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(), 5555);
BufferedReader reader = new BufferedReader(new FileReader("haha.txt"));
OutputStream outputStream = socket.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
String s=null;
while((s=reader.readLine())!=null){
writer.write(s); //每次写入一行
writer.newLine(); //换行
writer.flush(); //刷新
}
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
int read = inputStream.read(bytes);
String s1 = new String(bytes, 0, read);
System.out.println(s1);
}
}
服务类:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket socket = new ServerSocket(5555);
int i=1;
while (true){
Socket accept = socket.accept();//不断监听通道
new ServermyThread(accept).start();
System.out.println("第"+(i++)+"个用户传递文件");
}
}
}
服务线程类:
public class ServermyThread extends Thread {
Socket accept;
public ServermyThread(Socket accept) {
this.accept=accept;
}
@Override
public void run() {
try {
InputStream inputStream = accept.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
BufferedWriter writer = new BufferedWriter(new FileWriter(System.currentTimeMillis() + "hah.txt"));
String s=null;
while ((s=reader.readLine())!=null){
writer.write(s);
writer.newLine();
writer.flush();
}
OutputStream outputStream = accept.getOutputStream();
outputStream.write("文件已收到,请不要重复发送!!!".getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
URL:统一资源定位符
Java提供URL类,用来封装URL
格式:
1. URL DS=new URL(网络资源地址);
2.HttpURLConnection conn =(HttpURLConnection)DS.openConnection();//打开连接
相关方法:
Conn.setRequestMethod(“GET”);//设置请求方式
Conn.setConnectTimeout(3000);//设置请求超时间
int i =Conn.getResponseCode();//200 代表成功响应
Conn.getResponseMessage();//获取相应的信息
Conn.getContentLength()//获取资源文件大小
3. if(i==200){
4. 获取输入流进行读取
5. 建立输出流进行写}
6.释放资源
代码实现:
public class test {
public static void main(String[] args) throws IOException {
//资源地址
String url="http://img.redocn.com/sheji/20141219/zhongguofengdaodeliyizhanbanzhijing_3744115.jpg";
//封装
URL url1 = new URL(url);
HttpURLConnection con = (HttpURLConnection) url1.openConnection();
int i = con.getResponseCode();
/* String s = con.getResponseMessage(); //获取回应信息
int length = con.getContentLength(); //获取资源大小
System.out.println(i);
System.out.println(s);
System.out.println(length);*/
if(i==200){
InputStream stream = con.getInputStream();//获取输入流,读资源
FileOutputStream out = new FileOutputStream("photo.jpg");//创建输出流,对资源执行写操作
byte[] bytes = new byte[1024];
int len =0;
while ((len= stream.read(bytes))!=-1){
out.write(bytes,0,len);
out.flush();
}
stream.close();
out.close();
}
}
}