天天看點

網絡程式設計之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();
    }
}