网络编程三大基本概念
1.IP地址(计算机硬件的地址)
2.端口号port(计算机中特定软件的地址 如QQ:4000 tomcat:8080 Mysql:3306)
3.协议
UDP:面向无连接,数据不安全,速度快。不区分客户端与服务端。
TCP:面向连接(三次握手),数据安全,速度略低。分为客户端和服务端。
三次握手: 客户端先向服务端发起请求, 服务端响应请求, 传输数据
HTTP的底层就是TCP,同样遵循三次握手
Socket:插座?? 叫套接字
1.Socket由IP地址和端口号port组合在一起的唯一标示符
2.通信两端都有Socket
3.用于网络通信
4.两个Socket之间是由IO流实现的(上传 下载)
5.Socket在应用程序中创建,通过一种绑定机制与驱动程序建立关系,告诉自己所对应的IP和port
UDP传输代码:
发送端
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class Demo1_Send {
/**
* * 1.发送Send
* 创建DatagramSocket, 随机端口号
* 创建DatagramPacket, 指定数据, 长度, 地址, 端口
* 使用DatagramSocket发送DatagramPacket
* 关闭DatagramSocket
* @throws SocketException
* @throws UnknownHostException
*/
public static void main(String[] args) throws Exception {
String str = "what are you 弄啥呢?";
DatagramSocket socket = new DatagramSocket(); //创建Socket相当于创建码头
DatagramPacket packet = //创建Packet相当于集装箱
new DatagramPacket(str.getBytes(), str.getBytes().length, InetAddress.getByName("127.0.0.1"), 6666);
socket.send(packet); //发货,将数据发出去
socket.close(); //关闭码头
}
}
接收端
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Demo1_Receive {
/**
** 2.接收Receive
* 创建DatagramSocket, 指定端口号
* 创建DatagramPacket, 指定数组, 长度
* 使用DatagramSocket接收DatagramPacket
* 关闭DatagramSocket
* 从DatagramPacket中获取数据
* @throws Exception
*/
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6666); //创建Socket相当于创建码头
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);//创建Packet相当于创建集装箱
socket.receive(packet); //接货,接收数据
byte[] arr = packet.getData(); //获取数据
int len = packet.getLength(); //获取有效的字节个数
System.out.println(new String(arr,0,len));
socket.close();
String ip = packet.getAddress().getHostAddress();
int port = packet.getPort();
System.out.println("ip="+ip);
System.out.println("port="+port);
}
}
在eclipse项目里的bin目录下 shift+鼠标右键启动window PowerShell (cmd的超集)
也可以win+x启动!!不过要自己去弄路径 操作和cmd一样
接受端先启动
然后启动发送端
然后就实现了自己和自己的socket通信了
升级版
ps:主动忽略博主的无聊
发送端
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Demo2_Send {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in); //创建键盘录入对象
DatagramSocket socket = new DatagramSocket(); //创建Socket相当于创建码头
while(true) {
String line = sc.nextLine(); //获取键盘录入的字符串
if("quit".equals(line)) {
break;
}
DatagramPacket packet = //创建Packet相当于集装箱
new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"), 6666);
socket.send(packet); //发货,将数据发出去
}
socket.close(); //关闭码头
}
}
接收端
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Demo2_Receive {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6666); //创建Socket相当于创建码头
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);//创建Packet相当于创建集装箱
while(true) {
socket.receive(packet); //接货,接收数据
byte[] arr = packet.getData(); //获取数据
int len = packet.getLength(); //获取有效的字节个数
String ip = packet.getAddress().getHostAddress(); //获取ip地址
int port = packet.getPort(); //获取端口号
System.out.println(ip + ":" + port + ":" + new String(arr,0,len));
}
}
}
TCP协议代码
服务端和客户端
切记服务器一定是多线程的
客户端
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Test1_Client {
/**
* 客户端向服务器写字符串(键盘录入),服务器(多线程)将字符串反转后写回,客户端再次读取到是反转后的字符串
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
Scanner sc = new Scanner(System.in); //创建键盘录入对象
Socket socket = new Socket("127.0.0.1", 54321); //创建客户端,指定ip地址和端口号
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //获取输入流
PrintStream ps = new PrintStream(socket.getOutputStream());//获取输出流
ps.println(sc.nextLine()); //将字符串写到服务器去
System.out.println(br.readLine()); //将反转后的结果读出来
socket.close();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Test1_Server {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(54321);
System.out.println("服务器启动,绑定54321端口");
while(true) {
final Socket socket = server.accept(); //接受客户端的请求
new Thread() { //开启一条线程
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //获取输入流
PrintStream ps = new PrintStream(socket.getOutputStream());//获取输出流
String line = br.readLine(); //将客户端写过来的数据读取出来
line = new StringBuilder(line).reverse().toString(); //链式编程
ps.println(line); //反转后写回去
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
}
文件上传
客户端
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Test2_UpdateClient {
/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
// 1.提示输入要上传的文件路径, 验证路径是否存在以及是否是文件夹
File file = getFile();
// 2.发送文件名到服务端
Socket socket = new Socket("127.0.0.1", 12345);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println(file.getName());
// 6.接收结果, 如果存在给予提示, 程序直接退出
String result = br.readLine(); //读取存在后不存在的结果
if("存在".equals(result)) {
System.out.println("您上传的文件已经存在,请不要重复上传");
socket.close();
return;
}
// 7.如果不存在, 定义FileInputStream读取文件, 写出到网络
FileInputStream fis = new FileInputStream(file);
byte[] arr = new byte[8192];
int len;
while((len = fis.read(arr)) != -1) {
ps.write(arr, 0, len);
}
fis.close();
socket.close();
}
private static File getFile() {
Scanner sc = new Scanner(System.in); //创建键盘录入对象
System.out.println("请输入一个文件路径:");
while(true) {
String line = sc.nextLine();
File file = new File(line);
if(!file.exists()) {
System.out.println("您录入的文件路径不存在,请重新录入:");
}else if(file.isDirectory()) {
System.out.println("您录入的是文件夹路径,请输入一个文件路径:");
}else {
return file;
}
}
}
}
服务器端
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Test1_Server {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(54321);
System.out.println("服务器启动,绑定54321端口");
while(true) {
final Socket socket = server.accept(); //接受客户端的请求
new Thread() { //开启一条线程
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //获取输入流
PrintStream ps = new PrintStream(socket.getOutputStream());//获取输出流
String line = br.readLine(); //将客户端写过来的数据读取出来
line = new StringBuilder(line).reverse().toString(); //链式编程
ps.println(line); //反转后写回去
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
}