单聊与群聊

一对一聊天(TCP)

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
 
public class TCPServer {
 
    private List clients = new ArrayList<>();
 
    public static void main(String[] args) {
        new TCPServer().startServer();
    }
 
    public void startServer() {
        try {
            ServerSocket serverSocket = new ServerSocket(12345);
            System.out.println("Server listening on port 12345");
 
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("New client connected: " + clientSocket);
 
                ClientHandler clientHandler = new ClientHandler(clientSocket);
                clients.add(clientHandler);
 
                Thread thread = new Thread(clientHandler);
                thread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    private class ClientHandler implements Runnable {
        private Socket clientSocket;
        private InputStream inputStream;
        private OutputStream outputStream;
 
        public ClientHandler(Socket clientSocket) {
            this.clientSocket = clientSocket;
            try {
                this.inputStream = clientSocket.getInputStream();
                this.outputStream = clientSocket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
        @Override
        public void run() {
            try {
                while (true) {
                    byte[] buffer = new byte[1024];
                    int bytesRead = inputStream.read(buffer);
                    if (bytesRead == -1) {
                        break;
                    }
 
                    String receivedMessage = new String(buffer, 0, bytesRead);
                    System.out.println("Received from " + clientSocket + ": " + receivedMessage);
 
                    broadcastMessage(receivedMessage);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    clientSocket.close();
                    clients.remove(this);
                    System.out.println("Connection closed: " + clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
 
        public void sendMessage(String message) {
            try {
                outputStream.write(message.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    private void broadcastMessage(String message) {
        for (ClientHandler client : clients) {
            client.sendMessage(message);
        }
    }
}

客户端

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
 
public class TCPClient extends JFrame {
 
    private JTextArea chatArea;
    private JTextField messageField;
    private JButton sendButton;
 
    private Socket socket;
    private InputStream inputStream;
    private OutputStream outputStream;
 
    public static void main(String[] args) {
        new TCPClient().startClient();
    }
 
    public void startClient() {
        try {
            socket = new Socket("localhost", 12345);
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        SwingUtilities.invokeLater(() -> {
            initialize();
            startMessageReceiver();
            setVisible(true);
        });
    }
 
    private void initialize() {
        setTitle("TCP Chat Client");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(chatArea);
 
        messageField = new JTextField();
        sendButton = new JButton("Send");
 
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });
 
        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(messageField, BorderLayout.SOUTH);
        add(sendButton, BorderLayout.EAST);
    }
 
    private void startMessageReceiver() {
        Thread receiverThread = new Thread(() -> {
            try {
                while (true) {
                    byte[] buffer = new byte[1024];
                    int bytesRead = inputStream.read(buffer);
                    if (bytesRead == -1) {
                        break;
                    }
 
                    String receivedMessage = new String(buffer, 0, bytesRead);
                    appendToChatArea(receivedMessage);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
 
        receiverThread.start();
    }
 
    private void sendMessage() {
        try {
            String message = messageField.getText();
            outputStream.write(message.getBytes());
            messageField.setText("");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    private void appendToChatArea(String message) {
        SwingUtilities.invokeLater(() -> {
            chatArea.append(message + "\n");
        });
    }
}
群聊(UDP)

服务器端

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
 
public class UDPServer {
 
    private List clients = new ArrayList<>();
 
    public static void main(String[] args) {
        new UDPServer().startServer();
    }
 
    public void startServer() {
        try {
            DatagramSocket serverSocket = new DatagramSocket(12346);
            System.out.println("Server listening on port 12346");
 
            while (true) {
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);
 
                String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("Received from " + receivePacket.getAddress() + ": " + message);
 
                broadcastMessage(message, receivePacket.getAddress());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    private void broadcastMessage(String message, InetAddress senderAddress) {
        for (ClientHandler client : clients) {
            if (!client.getAddress().equals(senderAddress)) {
                client.sendMessage(message);
            }
        }
    }
 
    private class ClientHandler {
        private InetAddress address;
        private int port;
 
        public ClientHandler(InetAddress address, int port) {
            this.address = address;
            this.port = port;
        }
 
        public InetAddress getAddress() {
            return address;
        }
 
        public int getPort() {
            return port;
        }
 
        public void sendMessage(String message) {
            try {
                DatagramSocket socket = new DatagramSocket();
                byte[] sendData = message.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port);
                socket.send(sendPacket);
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

客户端

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
 
public class UDPClient extends JFrame {
 
    private JTextArea chatArea;
    private JTextField messageField;
    private JButton sendButton;
 
    private DatagramSocket socket;
    private InetAddress serverAddress;
    private int serverPort = 12346; // Use a different port for UDP
 
    public static void main(String[] args) {
        new UDPClient().startClient();
    }
 
    public void startClient() {
        try {
            socket = new DatagramSocket();
            serverAddress = InetAddress.getByName("localhost");
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        SwingUtilities.invokeLater(() -> {
            initialize();
            startMessageReceiver();
            setVisible(true);
        });
    }
 
    private void initialize() {
        setTitle("UDP Chat Client");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(chatArea);
 
        messageField = new JTextField();
        sendButton = new JButton("Send");
 
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });
 
        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(messageField, BorderLayout.SOUTH);
        add(sendButton, BorderLayout.EAST);
    }
 
    private void startMessageReceiver() {
        Thread receiverThread = new Thread(() -> {
            try {
                while (true) {
                    byte[] receiveData = new byte[1024];
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                    socket.receive(receivePacket);
 
                    String receivedMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
                    appendToChatArea(receivedMessage);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
 
        receiverThread.start();
    }
 
    private void sendMessage() {
        try {
            String message = messageField.getText();
            byte[] sendData = message.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, serverPort);
            socket.send(sendPacket);
            messageField.setText("");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    private void appendToChatArea(String message) {
        SwingUtilities.invokeLater(() -> {
            chatArea.append(message + "\n");
        });
    }
}

单聊与群聊_第1张图片

你可能感兴趣的:(java)