网络编程之java简易聊天室实现

最近浅学习了一些关于网络编程方面的知识,视频是跟着狂神学习的,可能学习的不是很深

说到网络,相信大家都对TCP、UDP和HTTP协议这些都不是很陌生,学习这部分应该先对端口、Ip地址这些基础知识有一定了解,后面我们都是直接上demo来解释代码

文件传输

Tcp方式

这里我们指的是C/S架构的文件传输,需要涉及一个客户端Client和服务器端(Server),这里采用的是TCP协议进行传输的,TCP需要经过三次握手和四次挥手,需要注意的是Client上传文件我们需要告诉服务器,我已经传输完成了socket.shutdownOutput()。

服务器 服务器 服务器


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

/**
 * @author dy
 * 2022/11/5 22:33
 */
public class TestServerUpload {

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

        ServerSocket serverSocket = new ServerSocket(9999);
        Socket socket = serverSocket.accept();

        // 或去输入
        InputStream is = socket.getInputStream();
        FileOutputStream outputStream = new FileOutputStream(new File("receive.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        OutputStream outputStream1 = socket.getOutputStream();
        outputStream1.write("我接收完毕了".getBytes());
        is.close();
        outputStream.close();
        serverSocket.close();
        serverSocket.close();
        
outputStream1.close();
    }
}

客户端 客户端 客户端

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

/**
 * @author dy
 * 2022/11/5 22:34
 */
public class TestClientUpload {

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

        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
        // 创建输出流
        OutputStream outputStream = socket.getOutputStream();
        FileInputStream fileInputStream = new FileInputStream(new File("1.jpg"));
        byte[] buffer = new byte[1024];

        int len;
        while (((len = fileInputStream.read(buffer))) != -1) {
            outputStream.write(buffer, 0, len);
        }

        // 通知服务器我已经结束了
        socket.shutdownOutput();

        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] buffer2 = new byte[1024];
        int len2;
        while ((len2 = inputStream.read(buffer2)) != -1) {
            baos.write(buffer2, 0, len2);
        }
        System.out.println(baos.toString());

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

Udp 方式

UDP是一种只管发送,不需要确保你已经接收的通信协议,就比如短信,我只管发送给您,但是不管有没有接收到。

public class UdpClient {

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

        // 1. 建包
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();
        } catch (SocketException e) {
            e.printStackTrace();
        }

        // 2. 建个包
        String msg = "早安呀,大勇";
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9999;
        DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);

        // 3. 发送包
        socket.send(datagramPacket);
        socket.close();
    }
}

public class UdpServer {

    public static void main(String[] args) throws Exception{
        // 开发端口
        DatagramSocket socket = new DatagramSocket(9999);

        // 收包
        byte[] buffer = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);
        // 阻塞接收
        socket.receive(datagramPacket);

        System.out.println(new String(datagramPacket.getData(), 0, datagramPacket.getLength()));
        System.out.println(datagramPacket.getAddress().getHostAddress());
        socket.close();
    }
}

简易聊天室的实现

接收端 接收端 接收端

public class TalkReceive implements Runnable {

    DatagramSocket socket;
    private int port;
    private String msgFrom;
    public TalkReceive(int port, String msgFrom) {
        this.msgFrom = msgFrom;
        this.port = port;
        try {
            socket = new DatagramSocket(port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        while (true) {
            try {
                byte[] buffer = new byte[1024];
                DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);
                socket.receive(datagramPacket);
                if (datagramPacket.getLength() > 0) {
                    byte[] data = datagramPacket.getData();
                    String receiveDatas = new String(data, 0, data.length);

                    System.out.println("接收到了"+ msgFrom + receiveDatas);
                    if ("bye".equals(receiveDatas)) {
                        break;
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
        socket.close();

    }
}

发送端 发送端 发送端

public class TalkSend implements Runnable {

    DatagramSocket socket = null;

    private int fromPort;
    private String toIp;
    private int toPort;
    BufferedReader reader = null;

    public TalkSend(int fromPort, String toIp, int port) {
        this.fromPort = fromPort;
        this.toIp = toIp;
        this.toPort = port;
        try {
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        while (true) {
            try {
                String data = reader.readLine();
                byte[] datas = data.getBytes();

                DatagramPacket packet = new DatagramPacket(datas, 0, data.length(), new InetSocketAddress(this.toIp, toPort));
                socket.send(packet);
                if ("bye".equals(data)) {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 数据
        }
        socket.close();

    }
}

启动 启动 启动

public class TalkStudent {

    public static void main(String[] args) {
        new Thread(new TalkSend(7777, "localhost", 9999)).start();
        new Thread(new TalkReceive(8888, "老师")).start();
    }
}
public class TalkTeacher {

    public static void main(String[] args) {
        new Thread(new TalkSend(5555, "localhost", 8888)).start();
        new Thread(new TalkReceive(9999, "学生")).start();
    }
}
posted @ 2022-11-06 09:12  Leo哥coding~  阅读(22)  评论(0编辑  收藏  举报  来源