文章目录
InetAddress的使用
package JavaInternetPrograming.QianFeng;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Demo01 {
public static void main(String[] args) throws IOException {
// 1.创建本地IP对象
// 1.1 getLocalhost()方法
InetAddress ia1 = InetAddress.getLocalHost();
System.out.println("Ip地址:" + ia1.getHostAddress() + ", 主机名" + ia1.getHostName());
// 1.2 getByName("IP地址")方法
InetAddress ia2 = InetAddress.getByName("169.254.195.255");
System.out.println("Ip地址:" + ia2.getHostAddress() + ", 主机名" + ia2.getHostName());
// 1.3 getByName("127.0.0.1")方法 //127.0.0.1表示本机
InetAddress ia3 = InetAddress.getByName("127.0.0.1");
System.out.println("Ip地址:" + ia2.getHostAddress() + ", 主机名" + ia2.getHostName());
// 1.3 getByName("localhost")方法 //localhost表示本机
InetAddress ia4 = InetAddress.getByName("localhost");
System.out.println("Ip地址:" + ia4.getHostAddress() + ", 主机名" + ia4.getHostName());
// 2.创建局域网IP对象
InetAddress ia5 = InetAddress.getByName("192.168.0.4");
System.out.println("两秒钟是否可达:"+ia5.isReachable(2000));// 判断是否可达,单位为毫秒,这里的2000表示2秒
System.out.println("Ip地址:" + ia5.getHostAddress() + ", 主机名" + ia5.getHostName());
// 3.创建外网IP地址对象
InetAddress ia6 = InetAddress.getByName("www.baidu.com");
System.out.println("两秒钟是否可达:"+ia6.isReachable(2000));// 判断是否可达,单位为毫秒,这里的2000表示2秒
System.out.println("Ip地址:" + ia6.getHostAddress() + ", 主机名" + ia6.getHostName());
// 获取目标服务器的所有地址
InetAddress[] ias = InetAddress.getAllByName("www.baidu.com");
for ( InetAddress i: ias
) {
System.out.println(i);
}
}
}
基于TCP的网络编程
TCP编程实现客户端发送数据给服务器端
TCP服务器端
package JavaInternetPrograming.QianFeng;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author kingdeguo
* 服务器端:
* 创建ServerSocket, 指定端口号
* 调用accept等待客户端接入
* 使用输入流,接收请求数据到服务器端(等待)
* 使用输出流,发送响应数据给客户端 (可选)
* 释放资源
* */
public class TcpServer {
public static void main(String[] args) throws IOException {
// 创建ServerSocket, 指定端口号
ServerSocket listener = new ServerSocket(8899);
// 调用accept等待客户端接入
// 是一个阻塞方法,即:如果没有客户端请求,则会一直等待
// 注意返回值是一个客户端Socket
Socket socket = listener.accept();
// 使用输入流,接收请求数据到服务器端(等待)
InputStream inputStream = socket.getInputStream();
// 为了能够接受中文,需要创建一个转换流
// 将字节流转化为字符流
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
String data = bufferedReader.readLine();
System.out.println("客户端发送的数据:" + data);
// 释放资源
bufferedReader.close();
socket.close();
listener.close();
}
}
TCP客户端
package JavaInternetPrograming.QianFeng;
import java.io.*;
import java.net.Socket;
/**
* @author kingdeguo
* 客服端:
* 创建Socket,指定服务器IP + 端口号
* 使用输出流, 发送请求数据给服务器
* 使用输入流, 读取服务器回复的数据
* 关闭资源
* */
public class TcpClient {
public static void main(String[] args) throws IOException {
// 创建Socket,指定服务器IP + 端口号
Socket socket = new Socket("192.168.137.1",8899);
// 使用输出流, 发送请求数据给服务器
OutputStream outputStream = socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
bufferedWriter.write("好久不见");
// 使用输入流, 读取服务器回复的数据(可选)
// 关闭资源
bufferedWriter.close();
socket.close();
}
}
运行
运行时先运行服务器端,再运行客户端。
客户端发送的数据:好久不见
TCP编程实现客户端上传文件给服务器
TCP服务器端
package JavaInternetPrograming.QianFeng;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpFileUploadServer {
public static void main(String[] args) throws IOException {
// 1.创建ServerSocket
ServerSocket listener = new ServerSocket(9999);
// 2.监听,接受客服端请求
Socket socket = listener.accept();
// 3.获取输入流
InputStream inputStream = socket.getInputStream();
// 4.边读取,边保存
FileOutputStream fos = new FileOutputStream("d:\\002.jpg");
byte[] buf = new byte[1024 * 4];
int count = 0;
while ((count = inputStream.read(buf)) != -1) {
fos.write(buf,0,count);
}
// 5.关闭资源
fos.close();
inputStream.close();
socket.close();
System.out.println("接受完毕");
}
}
TCP客户端
package JavaInternetPrograming.QianFeng;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class TcpFileUploadClient {
public static void main(String[] args) throws IOException {
// 1.创建Soctet
Socket socket = new Socket("192.168.137.1", 9999);
// 2.获取输出流
OutputStream outputStream = socket.getOutputStream();
// 3.边读取文件,边发送文件
FileInputStream fileInputStream = new FileInputStream("d:\\001.jpg");
byte[] buf = new byte[1024 * 4];
int count=0;
while ((count=fileInputStream.read(buf))!=-1) {
outputStream.write(buf,0,count);
}
// 4.关闭资源
fileInputStream.close();
socket.close();
System.out.println("发送成功");
}
}
TCP编程实现多个客户端发送数据给服务器
多线程套接字
package JavaInternetPrograming.QianFeng;
import java.io.*;
import java.net.Socket;
public class ScoketThread extends Thread {
private Socket socket;
public ScoketThread(Socket socket) {
this.socket = socket;
}
@Override
public void run(){
if (socket != null) {
BufferedReader bufferedReader = null;
try {
InputStream inputStream = socket.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
while (true) {
String data = bufferedReader.readLine();
if (data == null) {
break;
}
System.out.println(socket.getInetAddress()+"说"+data);
if (data.equals("886") || data.equals("Bye")) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bufferedReader.close();
socket.close();
System.out.println(socket.getInetAddress()+"退出了");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
TCP服务器端
package JavaInternetPrograming.QianFeng;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPMultiServer {
public static void main(String[] args) throws IOException {
// 1.创建ServerSocket
ServerSocket listener = new ServerSocket(10086);
// 2.调用accept(),接收客户端请求
// 3.为了接受多个客户端,这里用到while循环
System.out.println("服务器已启动......");
while (true) {
Socket socket = listener.accept();
System.out.println(socket.getInetAddress()+"进来了.....");
// 创建线程对象
// 负责接收数据
new ScoketThread(socket).start();
}
}
}
TCP客户端
package JavaInternetPrograming.QianFeng;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;
public class TCPMultiClient {
public static void main(String[] args) throws IOException {
// 1.创建Socket
Socket socket = new Socket("192.168.137.1", 10086);
// 2.获取输出流
OutputStream outputStream = socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
// 3.控制台输入
Scanner input = new Scanner(System.in);
while (true) {
String data = input.nextLine();
bufferedWriter.write(data);
//发送换行符
bufferedWriter.newLine();
bufferedWriter.flush();
if (data.equals("886") || data.equals("Bye")) {
break;
}
}
bufferedWriter.close();
socket.close();
}
Socket编程实现注册登录
注册线程
package JavaInternetPrograming.QianFeng;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
public class RegistThread extends Thread{
@Override
public void run(){
try {
// 1.创建一个ServerSocket
ServerSocket linstener = new ServerSocket(6666);
// 2.调用accept方法
System.out.println("服务器注册已启动......");
Socket socket = linstener.accept();
// 3.获取输入输出流
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
// 4.接收客户端发送的数据
// 这里用到的格式为: {id:1001, name:tom, pwd:123, age:20}
String json = bufferedReader.readLine();
String[] infos = json.substring(1, json.length() - 1).split(",");
String id = infos[0].split(":")[1];
// 5.加载数据文件
Properties properties = Tools.loadProperties();
// 6.判断
if (properties.containsKey(id)) {
bufferedWriter.write("此用户已存在");
} else {
// 保存属性文件
Tools.saveProperties(json);
bufferedWriter.write("注册成功");
}
bufferedWriter.newLine();
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
socket.close();
linstener.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
登录线程
package JavaInternetPrograming.QianFeng;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
public class LoginThread extends Thread {
@Override
public void run() {
try {
// 1.创建一个ServerSocket
ServerSocket linstener = new ServerSocket(6666);
// 2.调用accept方法
System.out.println("服务器注册已启动......");
Socket socket = linstener.accept();
// 3.获取输入输出流
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
// 4.接收客户端发送的数据
// 这里用到的格式为: {id:1001, name:tom, pwd:123, age:20}
String json = bufferedReader.readLine();
String[] infos = json.substring(1, json.length() - 1).split(",");
String id = infos[0].split(":")[1];
// 5.加载数据文件
Properties properties = Tools.loadProperties();
// 6.判断
if (properties.containsKey(id)) {
// 判断密码是否正确
String pwd = infos[1].split(":")[1];
String value = properties.getProperty(id);
String[] arr = value.substring(1, value.length() - 1).split(",");
String pwd2 = arr[2].split(":")[1];
if (pwd.equals(pwd2)) {
bufferedWriter.write("登录成功");
} else {
bufferedWriter.write("密码错误");
}
} else {
bufferedWriter.write("用户名错误");
}
bufferedWriter.newLine();
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
socket.close();
linstener.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
工具类
package JavaInternetPrograming.QianFeng;
import java.io.*;
import java.util.Properties;
public class Tools {
// 1.加载属性文件
public static Properties loadProperties() throws IOException {
// 1. 创建属性集合
Properties properties = new Properties();
// 2.判断文件是否存在
File file = new File("users.properties");
if (file.exists()) {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
properties.load(fileInputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
}
// 2.保存属性文件
public static void saveProperties(String json) throws IOException {
String[] infos = json.substring(1, json.length() - 1).split(",");
String id = infos[0].split(":")[1];
//保存
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream("users.properties", true);
Properties properties = new Properties();
properties.setProperty(id, json);
properties.store(fileOutputStream,"");
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
用户类
package JavaInternetPrograming.QianFeng;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class UserClient {
public static void main(String[] args) throws IOException {
System.out.println("---请选择:1,注册 2,登录---");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
switch (choice) {
case 1:regist();
break;
case 2:login();
break;
}
}
public static void regist() throws IOException {
// 1.创建socket
Socket socket = new Socket("192.168.137.1", 6666);
// 2.获取流
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
// 3.获取用户信息
String jsom = getRegistInfo();
// 4.发送
bufferedWriter.write(jsom);
bufferedWriter.newLine();
bufferedWriter.flush();
// 5.接收
String reply = bufferedReader.readLine();
System.out.println("服务器回复:" + reply);
// 6.关闭
bufferedWriter.close();
bufferedReader.close();
socket.close();
}
public static String getRegistInfo(){
Scanner input = new Scanner(System.in);
System.out.println("请输入编号");
int id = input.nextInt();
System.out.println("请输入姓名");
String name = input.next();
System.out.println("请输入密码");
String pwd = input.next();
System.out.println("请输入年龄");
int age = input.nextInt();
String json = "{id:" + id + ", name:" + name + ", pwd:" + pwd + ", age:" + age + "}";
return json;
}
public static String login() throws IOException {
Scanner input = new Scanner(System.in);
System.out.println("请输入编号");
int id = input.nextInt();
System.out.println("请输入姓名");
String name = input.next();
System.out.println("请输入密码");
String pwd = input.next();
System.out.println("请输入年龄");
int age = input.nextInt();
String json = "{id:" + id + ", pwd:" + pwd + "}";
return json;
}
public static String getLoginInfo() throws IOException {
// 1.创建socket
Socket socket = new Socket("192.168.137.1", 6666);
// 2.获取流
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
// 3.获取用户信息
String jsom = getLoginInfo();
// 4.发送
bufferedWriter.write(jsom);
bufferedWriter.newLine();
bufferedWriter.flush();
// 5.接收
String reply = bufferedReader.readLine();
System.out.println("服务器回复:" + reply);
// 6.关闭
bufferedWriter.close();
bufferedReader.close();
socket.close();
return jsom;
}
}