首页 > 编程语言 >Java网络编程Socket

Java网络编程Socket

时间:2022-10-06 20:00:35浏览次数:85  
标签:java Socket 编程 System Java import println new socket

Java网络多线程

2022年8月31日

笔记 韩顺平Java自学笔记 网络多线程_关注永雏塔菲喵的博客-CSDN博客

网课 【韩顺平讲Java】Java网络多线程专题 - TCP UDP Socket编程 多线程 并发处理 文件传输 新闻推送 Java_哔哩哔哩_bilibili

通信项目上传到github:cxy-sky/JavaSocket: Java 网络多线程专题,包括 TCP UDP Socket编程 多线程 并发处理 文件传输 新闻推送 (github.com)
2022年9月7日完结

InetAddress

package com.jiao;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {

    public static void main(String[] args) throws UnknownHostException {
//       获得本机的InetAddress对象
        InetAddress localHost = InetAddress.getLocalHost();
        System.out.println(localHost);
//      根据指定的主机名获得InetAddress对象
        InetAddress byName = InetAddress.getByName("sky");
        System.out.println(byName);
//      根据域名返回对应的ip
        InetAddress byName1 = InetAddress.getByName("www.baidu.com");
        System.out.println(byName1);
//      通过getHostAddress对象使他获得对应的地址ipv4地址
        String hostAddress = byName1.getHostAddress();
        System.out.println(hostAddress);
//      获取对应的域名
        String hostName = byName1.getHostName();
        System.out.println(hostName);
    }
}

Socket

简介

请添加图片描述

理解

请添加图片描述

TCP网络通信

简介

请添加图片描述

案例1 字节流

服务端

package com.jiao.socket.tcp01;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * auth:@highSky
 * create:2022/8/31
 * email:[email protected]
 **/
public class Server {

    public static void main(String[] args) throws IOException {

//        要求电脑上没有其他程序在监听9999接口
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务器在9999端口进行监听");
        //程序阻塞,不再向下执行  如果有客户端socket链接,返回一个socket链接,开始向下执行
        Socket socket = serverSocket.accept();
        System.out.println("客户端 socket = "+socket.getClass());
//      客户端没有发送消息的话,会堵塞在这里
        InputStream inputStream = socket.getInputStream();
        byte[] msg = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(msg)) != -1) {
            System.out.println("收到消息: " + socket.getLocalAddress().getHostName() + " " + new String(msg, 0, len));
        }
        inputStream.close();
        socket.close();
        serverSocket.close();
        System.out.println("服务关闭");
    }

}

客户端

package com.jiao.socket.tcp01;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * auth:@highSky
 * create:2022/8/31
 * email:[email protected]
 **/
public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(InetAddress.getLocalHost().getHostAddress(), 9999);
        System.out.println("正在发送消息");
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello jiaojiao".getBytes());
        //发送完成结束标记
        socket.shutdownOutput();
        System.out.println("消息发送完成");
        outputStream.close();
        socket.close();
    }
}

案例2 互发消息

server

package com.jiao.socket.tcp02;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * auth:@highSky
 * create:2022/8/31
 * email:[email protected]
 **/
public class Server {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("server" + InetAddress.getLocalHost().getHostAddress() + "正在监听");
        Socket socket = serverSocket.accept();
        InputStream inputStream = socket.getInputStream();
        byte[] msg = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(msg)) != -1) {
            System.out.println("收到消息: " + socket.getLocalAddress().getHostName() + " " + new String(msg, 0, len));
        }
        
		//给client发送消息
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello tiantian".getBytes());
        //发送完成结束标记
        socket.shutdownOutput();

        outputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
        System.out.println("服务关闭");
    }

}

client

package com.jiao.socket.tcp02;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * auth:@highSky
 * create:2022/8/31
 * email:[email protected]
 **/
public class Client {
    public static void main(String[] args) throws IOException {
//        Socket socket = new Socket("106.14.219.106", 9999);
        Socket socket = new Socket(InetAddress.getLocalHost().getHostAddress(), 9999);
        System.out.println("正在发送消息");
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello jiaojiao".getBytes());
        //发送完成结束标记
        socket.shutdownOutput();
        System.out.println("消息发送完成");

        //接收服务端发来的消息
        InputStream inputStream = socket.getInputStream();
        byte[] msg = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(msg)) != -1) {
            System.out.println(new String(msg, 0, len));
        }

        inputStream.close();
        outputStream.close();
        socket.close();
    }
}

案例3 字节流

使用writer时,写入数据后,要调用flush刷新

//input字节流转换为reader字符流
InputStream inputStream = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//output字节流转换为writer字符流
OutputStream outputStream = socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
package com.jiao.socket.tcp03;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * auth:@highSky
 * create:2022/8/31
 * email:[email protected]
 **/
public class Server {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("server" + InetAddress.getLocalHost().getHostAddress() + "正在监听");
        Socket socket = serverSocket.accept();
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String msg = bufferedReader.readLine();
        System.out.println("server 收到消息: " + socket.getLocalAddress().getHostName() + " " + msg);

        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello tiantian");
        bufferedWriter.newLine();
        bufferedWriter.flush();

        bufferedWriter.close();
        bufferedReader.close();
        socket.close();
        serverSocket.close();
        System.out.println("服务关闭");
    }

}

客户端

package com.jiao.socket.tcp03;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * auth:@highSky
 * create:2022/8/31
 * email:[email protected]
 **/
public class Client {
    public static void main(String[] args) throws IOException {
//        Socket socket = new Socket("106.14.219.106", 9999);
        Socket socket = new Socket(InetAddress.getLocalHost().getHostAddress(), 9999);
        System.out.println("正在发送消息");
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello jiaojiao");
        bufferedWriter.newLine();
        bufferedWriter.flush();
        System.out.println("消息发送完成");

        //接收服务端发来的消息
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String msg = bufferedReader.readLine();
        System.out.println("client 收到消息: " + socket.getLocalAddress().getHostName() + " " + msg);

        bufferedReader.close();
        bufferedWriter.close();
        socket.close();
    }
}

上传文件

img

工具类

package com.jiao.upload;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
 * auth:@highSky
 * create:2022/9/1
 * email:[email protected]
 **/

public class StreamUtils {
    public static byte[] streamToByteArray(InputStream is) throws Exception {
        // 创建输出流对象
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        // 字节数组
        byte[] b = new byte[1024];
        int len;
        while ((len = is.read(b)) != -1) {
            // 循环读取
            // 把读取到的数据,写入 bos
            bos.write(b, 0, len);
        }
        byte[] array = bos.toByteArray();
        bos.close();
        return array;
    }

    public static String streamToString(InputStream is) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line + "\r\n");
        }
        return builder.toString();
    }
}

server

package com.jiao.upload;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * auth:@highSky
 * create:2022/9/1
 * email:[email protected]
 **/
public class Server {

    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("》》服务开启,等待连接,发送图片");
        //得到连接
        Socket socket = serverSocket.accept();
        //准备图片
        String imgName = "src/com/jiao/upload/jiaojiao.png";
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(imgName));
        //将图片保存为byte数组中
        byte[] img = StreamUtils.streamToByteArray(bis);
        //获取socket的输出流
        OutputStream outputStream = socket.getOutputStream();
        //转换为缓存输出流
        BufferedOutputStream bos = new BufferedOutputStream(outputStream);
        bos.write(img);
        System.out.println("》》图片发送完成");
        socket.shutdownOutput();

        //客户端收到图片后的反馈信息
        InputStream inputStream = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        System.out.println(reader.readLine());
        bos.close();
        bis.close();
        reader.close();
        socket.close();

    }

}

client

package com.jiao.upload;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * auth:@highSky
 * create:2022/9/1
 * email:[email protected]
 **/
public class Client {

    public static void main(String[] args) throws Exception {
        Socket socket = new Socket(InetAddress.getLocalHost().getHostAddress(), 9999);
        System.out.println("》》等待图片");

        //获取socket接收到的二进制图片数据
        InputStream inputStream = socket.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        byte[] img = StreamUtils.streamToByteArray(bis);

        //保存到本地
        String imgName = "src/com/jiao/upload/tiantian.png";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(imgName));
        bos.write(img);
        System.out.println("》》保存完成");


        //给服务端发送接受完成信息
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        writer.write(InetAddress.getLocalHost().getHostName() + "已收到图片");
        writer.newLine();
        writer.flush();
        writer.close();
        bos.close();
        bis.close();
        socket.close();

    }

}

UDP

原理

请添加图片描述

user1

package com.jiao.udp;

import java.io.IOException;
import java.net.*;

/**
 * auth:@highSky
 * create:2022/9/2
 * email:[email protected]
 **/
public class User1 {

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(9999);
        //向user2发送消息
        byte[] bag = new byte[1024];
        DatagramPacket packet = new DatagramPacket(bag, bag.length, InetAddress.getByName("192.168.1.3"), 9998);
        byte[] msg = "Hello jiaojiao".getBytes();
        packet.setData(msg, 0, msg.length);
        socket.send(packet);

        System.out.println("发送完成");
        System.out.println("等待user2回复");

        packet = new DatagramPacket(bag, bag.length);
        socket.receive(packet);
        msg = packet.getData();
        System.out.println(new String(msg, 0, msg.length));

        System.out.println("通信完成");
        socket.close();
    }
}

user2

package com.jiao.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * auth:@highSky
 * create:2022/9/2
 * email:[email protected]
 **/
public class User2 {

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(9998);
        //接受user1的消息
        byte[] bag = new byte[1024];
        DatagramPacket packet = new DatagramPacket(bag, bag.length);
        System.out.println("等待user1的消息");
        socket.receive(packet);
        byte[] msg = packet.getData();
        System.out.println(new String(msg, 0, msg.length));
        //回复user1
        packet = new DatagramPacket(bag, bag.length, InetAddress.getByName("192.168.1.3"), 9999);
        msg = "hello tiantian".getBytes();
        packet.setData(msg, 0, msg.length);
        socket.send(packet);
        System.out.println("通信结束");
        socket.close();
    }
}

练习

tcp

请添加图片描述

server

package com.jiao.homework.test1;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * auth:@highSky
 * create:2022/9/2
 * email:[email protected]
 **/
public class Server {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println(">>服务已开启,等待连接");
        Socket socket = serverSocket.accept();
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//        System.out.println("client:  " + reader.readLine());

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        if ("name".equals(reader.readLine()))
            writer.write("nova");
        else
            writer.write("你说啥呢");
        writer.newLine();
        writer.flush();

        System.out.println("client:  " + reader.readLine());

        writer.write("编写java程序");
        writer.newLine();
        writer.flush();

        writer.close();
        reader.close();
        socket.close();

    }
}

client

package com.jiao.homework.test1;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * auth:@highSky
 * create:2022/9/2
 * email:[email protected]
 **/
public class Client {

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(InetAddress.getLocalHost().getHostAddress(), 9999);
        System.out.println(">>给服务器发送消息");
        //给server发送消息
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        writer.write("name");
        writer.newLine();
        writer.flush();


        //接受回复
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//        System.out.println("server:  " + reader.readLine());
        if ("name".equals(reader.readLine()))
            writer.write("hobby");
        else
            writer.write("你说啥呢");
        writer.newLine();
        writer.flush();

        System.out.println("server:  " + reader.readLine());

        writer.close();
        reader.close();
        socket.close();

    }
}

udp

请添加图片描述

userA

package com.jiao.homework.udp;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * auth:@highSky
 * create:2022/9/2
 * email:[email protected]
 **/
public class UserA {

    public static void main(String[] args) throws IOException {

        Scanner in = new Scanner(System.in);

        //发送方
        DatagramSocket socket = new DatagramSocket(9999);

        byte[] bag = new byte[1024];
        DatagramPacket packet = new DatagramPacket(bag, bag.length, InetAddress.getByName("192.168.1.3"), 9998);
        System.out.println("请输入问题:");
        String msgS = in.nextLine();
        byte[] msgB = msgS.getBytes();
        packet.setData(msgB);
        socket.send(packet);

        packet = new DatagramPacket(bag, bag.length);
        socket.receive(packet);
        msgB = packet.getData();
        System.out.println(new String(msgB, 0, packet.getLength()));

        socket.close();
    }

}

userB

package com.jiao.homework.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * auth:@highSky
 * create:2022/9/2
 * email:[email protected]
 **/
public class UserB {


    public static void main(String[] args) throws IOException {
        //接受方
        DatagramSocket socket = new DatagramSocket(9998);
        byte[] bag = new byte[1024];
        DatagramPacket packet = new DatagramPacket(bag, bag.length);
        socket.receive(packet);
        byte[] msgB = packet.getData();
        System.out.println(new String(msgB, 0, packet.getLength()));

        packet = new DatagramPacket(bag, bag.length, InetAddress.getByName("192.168.1.3"), 9999);
        packet.setData("四大名著为。。。。。。".getBytes());
        socket.send(packet);

        socket.close();
    }
}

文件传输

请添加图片描述

server

package com.jiao.homework.trans;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * auth:@highSky
 * create:2022/9/3
 * email:[email protected]
 **/
public class Server {

    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(9999);
        //服务端等待客户端下载请求
        System.out.println("等待请求");
        Socket socket = serverSocket.accept();
        //得到socket请求
        InputStream is = socket.getInputStream();
        byte[] data = new byte[1024];
        int len = 0;
        //文件名称,这里是单线程可以用stringBuilder
        StringBuilder fileName = new StringBuilder();
        while ((len = is.read(data, 0, data.length)) != -1) {
            fileName.append(new String(data, 0, len));
        }
        System.out.println(fileName);
        BufferedInputStream bis = null;
        if ("碧蓝之海".equals(fileName.toString())) {
            fileName = new StringBuilder("src/com/jiao/homework/trans/碧蓝之海.mp3");
        } else {
            fileName = new StringBuilder("src/com/jiao/homework/trans/sorry.txt");
        }
        bis = new BufferedInputStream(new FileInputStream(fileName.toString()));
        byte[] file = StreamUtils.streamToByteArray(bis);

        //发送给客户端
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        bos.write(file);
        bos.flush();
        socket.shutdownOutput();

        bos.close();
        bis.close();
        socket.close();
        serverSocket.close();

    }
}

client

package com.jiao.homework.trans;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * auth:@highSky
 * create:2022/9/3
 * email:[email protected]
 **/
public class Client {

    public static void main(String[] args) throws Exception {

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入文件名");
        String filename = scanner.nextLine();
        //给服务端发送下载文件的文件名
        Socket socket = new Socket(InetAddress.getLocalHost().getHostAddress(), 9999);
        OutputStream os = socket.getOutputStream();
        os.write(filename.getBytes());
        os.flush();
        socket.shutdownOutput();
        //获取返回的文件,下载
        //将文件读取到数组中
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        byte[] file = StreamUtils.streamToByteArray(bis);
        //保存到本地
        if ("碧蓝之海".equals(filename))
            filename = "E:\\" + filename + ".mp3";
        else
            filename = "E:\\" + filename + ".txt";

        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filename));
        bos.write(file);
        bos.flush();

        bos.close();
        bis.close();
        os.close();
        socket.close();

    }
}

StreamUtils

package com.jiao.homework.trans;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * auth:@highSky
 * create:2022/9/1
 * email:[email protected]
 **/

public class StreamUtils {
    public static byte[] streamToByteArray(InputStream is) throws Exception {
        // 创建输出流对象
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        // 字节数组
        byte[] b = new byte[1024];
        int len;
        while ((len = is.read(b)) != -1) {
            // 循环读取
            // 把读取到的数据,写入 bos
            bos.write(b, 0, len);
        }
        byte[] array = bos.toByteArray();
        bos.close();
        return array;
    }

    public static String streamToString(InputStream is) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line + "\r\n");
        }
        return builder.toString();
    }
}

项目-多用户通信请添加图片描述

标签:java,Socket,编程,System,Java,import,println,new,socket
From: https://www.cnblogs.com/cxy-sky/p/sky01.html

相关文章

  • Java—多线程
    Java多线程基础概念进程与线程进程:操作系统分配资源的最小单位线程:CPU执行的最小单位线程分类1.用户线程用户自己创建的业务线程;2.守护线程......
  • java static 静态
    static是java语言中的关键字,意思是“静态的”,它可以用来修饰变量、方法、代码块等,修饰的变量叫做静态变量,修饰的方法叫做静态方法,修饰的代码块叫做静态代码块。static的......
  • 网络编程
    网络编程、OSI七层协议socket套接字编程、半连接层、粘包......
  • 「前端料包」深入理解JavaScript原型和原型链
    1.前言关于JS原型和原型链我之前刚学js就有写过一篇学习笔记形式的博客,但前两天翻出来一看——什么鬼,这是我写的吗?自己都看不懂了,于是我重新整理思路,今天「前端料包」......
  • java方法重载
    1234567891011121314151617如下代码:<br>//MethodOverload.java //Usingoverloadedmethods packageHJssss;public class zhuce{ ......
  • Java NIO通信基础
    参考书籍:Netty、Redis、ZooKeeper高并发实战1.  IO读写的基本原理用户程序进行IO的读写,实际上是缓存区的复制。即read:从内核缓冲区复制到进程缓冲区;write:从进行缓冲区......
  • 「前端料包」可能是最透彻的JavaScript数据类型详解
    前言接触写博客有一段时间了,都是边学边学着写,但总感觉写的凌乱,想起啥写啥。这几天在刷红宝书,收获还是蛮多的,决定结合自己的学习,写一个系列,我叫它「前端料包」,旨在巩固前端......
  • Java 面试题 05 - Spring Boot
    Spring是什么?是一个轻量级的控制反转和面向切面的容器框架。控制反转(IOC):一个对象所依赖的其他对象的创建,不由这个对象负责,而是由容器负责,容器会在对象初始化时就将所......
  • Flask框架:运用SocketIO实现WebSSH
    Flask框架中如果想要实现WebSocket功能有许多种方式,运用SocketIO库来实现无疑是最简单的一种方式,Flask中封装了一个flask_socketio库该库可以直接通过pip仓库安装,如下内容......
  • Java 面试题 06 - MySQL
    事务事务是逻辑上的一组操作,要么都执行,要么都不执行。事务的四个特性(ACID):原子性:事务不允许分割,要么全部完成,要么完全不执行。一致性:逻辑上的正确性,即这组操作的结果是......