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;
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;
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();
    }
}

到此這篇關於Java實現一個簡易聊天室流程的文章就介紹到這瞭,更多相關Java聊天室內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: