端口号范围:0~65535,建议选择1024以上
UDP:面向无连接,数据不安全,速度快,不区分客户端和服务器(有发送端和接收端)(发短信)
TCP:面向连接(三次握手),数据安全,速度略低,分为客户端和服务器(打电话)
1.UDP
package day26;
import java.io.IOException;
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 Dk1UdpSend {
//UDP发送端
public static void main(String[] args) throws IOException {
//basic();
advanced();
}
public static void basic() throws SocketException, UnknownHostException, IOException {
//1.创建DatagramSocket,随机端口号
DatagramSocket socket = new DatagramSocket();
//2.创建DatagramPacket,指定数据,长度,地址,端口
String str = "红鲤鱼绿鲤鱼与驴";
DatagramPacket packet = new DatagramPacket(str.getBytes(), str.getBytes().length,InetAddress.getByName("127.0.0.1"),12345);
//3.使用DatagramSocket发送DatagramPacket
socket.send(packet);
//4.关闭DatagramSocket
socket.close(); //底层是IO流所以要关
}
public static void advanced() throws SocketException, UnknownHostException, IOException {
//1.创建DatagramSocket,随机端口号
DatagramSocket socket = new DatagramSocket();
Scanner sc = new Scanner(System.in);
while (true) {
//2.创建DatagramPacket,指定数据,长度,地址,端口
String str = sc.nextLine();
if ("quit".equals(str)) {
break;
}
DatagramPacket packet = new DatagramPacket(str.getBytes(), str.getBytes().length,InetAddress.getByName("127.0.0.1"),12345);
//3.使用DatagramSocket发送DatagramPacket
socket.send(packet);
}
//4.关闭DatagramSocket
socket.close(); //底层是IO流所以要关
}
}
package day26;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Dk2UdpReceive {
//UDP接收端
public static void main(String[] args) throws IOException {
//basic();
advanced();
}
public static void basic() throws SocketException, IOException {
//1.创建DatagramSocket(码头),指定端口号
DatagramSocket socket = new DatagramSocket(12345);
//2.创建DatagramPacket(集装箱),指定数组,长度
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
//3.使用DatagramSocket接收DatagramPacket
socket.receive(packet);
//4.从DatagramPacket获取数据
byte[] arr = packet.getData();
int len = packet.getLength(); //获取发过来的有效字节个数
System.out.println(new String(arr,0,len)); //转换len个字节为字符串
//5.关闭DatagramSocket
socket.close();
}
public static void advanced() throws SocketException, IOException {
//1.创建DatagramSocket(码头),指定端口号
DatagramSocket socket = new DatagramSocket(12345);
//2.创建DatagramPacket(集装箱),指定数组,长度
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
while (true) {
//3.使用DatagramSocket接收DatagramPacket
socket.receive(packet);
//4.从DatagramPacket获取数据
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)); //转换len个字节为字符串
}
}
}
package day26;
import java.io.IOException;
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 Dk3UdpMoreThread {
//多线程
public static void main(String[] args) throws InterruptedException {
new UdpReceive().start();
Thread.sleep(10); //让接收端先启动
new UdpSend().start();
}
}
class UdpReceive extends Thread{
public void run() { //异常不能直接抛,用try
try {
//1.创建DatagramSocket(码头),指定端口号
DatagramSocket socket = new DatagramSocket(12345);
//2.创建DatagramPacket(集装箱),指定数组,长度
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
while (true) {
//3.使用DatagramSocket接收DatagramPacket
socket.receive(packet);
//4.从DatagramPacket获取数据
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)); //转换len个字节为字符串
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class UdpSend extends Thread{
public void run() {
try {
//1.创建DatagramSocket,随机端口号
DatagramSocket socket = new DatagramSocket();
Scanner sc = new Scanner(System.in);
while (true) {
//2.创建DatagramPacket,指定数据,长度,地址,端口
String str = sc.nextLine();
if ("quit".equals(str)) {
break;
}
DatagramPacket packet = new DatagramPacket(str.getBytes(), str.getBytes().length,InetAddress.getByName("127.0.0.1"),12345);
//3.使用DatagramSocket发送DatagramPacket
socket.send(packet);
}
//4.关闭DatagramSocket
socket.close(); //底层是IO流所以要关
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//输出
你好
127.0.0.1:57978:你好
你好
127.0.0.1:57978:你好
明天好
127.0.0.1:57978:明天好
2.TCP
package day26;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Dk4TcpServer {
//TCP服务端
public static void main(String[] args) throws IOException {
//basic();
//advanced();
moreThread();
}
public static void basic() throws IOException {
//1.创建ServerSocket(需要指定端口号)
ServerSocket server = new ServerSocket(9999);
//2.调用ServerSocket的accept()方法接收一个客户端请求,得到一个socket
Socket socket = server.accept();
//3.调用Socket的getInputStream()和getOutputStream()方法获取和客户端相连的IO流
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
//输出流可以写出数据到客户端的输入流
os.write("百度一下,你就知道".getBytes());
//输入流可以读取客户端输出流写出的数据
byte[] arr = new byte[1024];
int len = is.read(arr);
System.out.println(new String(arr,0,len));
//关闭套接字
socket.close();
}
public static void advanced() throws IOException {
//1.创建ServerSocket(需要指定端口号)
ServerSocket server = new ServerSocket(9999);
//2.调用ServerSocket的accept()方法接收一个客户端请求,得到一个socket
Socket socket = server.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("欢迎咨询"); //写给客户端
System.out.println(br.readLine());//读客户端
}
public static void moreThread() throws IOException {
//1.创建ServerSocket(需要指定端口号)
final ServerSocket server = new ServerSocket(9999);
while (true) {
//2.调用ServerSocket的accept()方法接收一个客户端请求,得到一个socket
Socket socket = server.accept();
new Thread() {
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("欢迎咨询"); //写给客户端
System.out.println(br.readLine());//读客户端
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}
}
package day26;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Dk5TcpClient {
//TCP客户端
public static void main(String[] args) throws IOException {
//basic();
advanced();
}
public static void basic() throws UnknownHostException, IOException {
//1.创建Socket连接客户端(指定IP地址和端口号),通过IP地址找对应的服务器
Socket socket = new Socket("127.0.0.1",9999);
//2.调用Socket的getInputStream()和getOutputStream()方法获取和服务端相连的IO流
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
//输入流可以读取服务端输出流写出的数据
byte[] arr = new byte[1024];
int len = is.read(arr);
System.out.println(new String(arr,0,len));
//输出流可以写出数据到服务端的输入流
os.write("学习挖掘机哪家强".getBytes());
//关闭套接字
socket.close();
}
public static void advanced() throws UnknownHostException, IOException {
//1.创建Socket连接客户端(指定IP地址和端口号),通过IP地址找对应的服务器
Socket socket = new Socket("127.0.0.1",9999);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
System.out.println(br.readLine()); //读服务器
ps.println("学Java"); //写给服务器
socket.close();
}
}
package day26;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class Dk7UploadClient {
//客户端向服务器上传文件
public static void main(String[] args) throws 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();
}
//1.上传文件路径
public 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;
}
}
}
}
package day26;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Dk6UploadServer {
//上传文件到服务端
public static void main(String[] args) throws IOException {
//3.建立多线程的服务器
ServerSocket server = new ServerSocket(12345);
System.out.println("服务器启动");
while (true) {
final Socket socket = server.accept();
new Thread() {
public void run() {
try {
//4.读取文件名
InputStream is = socket.getInputStream(); //读文件
BufferedReader br = new BufferedReader(new InputStreamReader(is)); //读文件名
PrintStream ps = new PrintStream(socket.getOutputStream());
String fileName = br.readLine();
File dir = new File("Upload");
dir.mkdir(); //创建文件夹
File file = new File(dir,fileName); //将文件名包装成file对象才可以进行判断
//5.判断文件是否存在,将结果发回客户端
if (file.exists()) {
ps.println("存在");
socket.close();
return;
}else {
ps.println("不存在");
}
//8.定义FileOutputStream,从网络读取数据存储到本地
FileOutputStream fos = new FileOutputStream(file);
byte[] arr = new byte[8192];
int len;
while((len = is.read(arr)) != -1) {
fos.write(arr,0,len);
}
fos.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}
}