[Java之socket应用实现]

目录

前言:

socket实现实时聊天代码只支持一对一的聊天:

客户端代码:

多个客户端连接聊天:

客户端代码与之前的代码相同,不需要做改变。


前言:

    记录一个笔记

socket实现实时聊天代码只支持一对一的聊天:

java.net.* 即可使用Socket类和相关方法。

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

public class Server {
    public static void main(String[] args) {
        try {
            // 创建ServerSocket对象,监听端口号为8888
            ServerSocket serverSocket = new ServerSocket(8888);
            
            System.out.println("Server is running...");
            
            // 等待客户端连接
            Socket socket = serverSocket.accept();
            System.out.println("Client connected.");
            
            // 创建输入流和输出流
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
            
            // 不断读取客户端发送的消息并回复
            while (true) {
                String message = reader.readLine();
                System.out.println("Message from client: " + message);
                writer.write("Server received message: " + message + "\n");
                writer.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客户端代码:

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

public class Client {
    public static void main(String[] args) {
        try {
            // 创建Socket对象,连接服务器的IP地址和端口号为8888
            Socket socket = new Socket("localhost", 8888);
            System.out.println("Connected to server.");
            
            // 创建输入流和输出流
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
            
            // 不断读取控制台输入的消息并发送给服务器
            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String message = console.readLine();
                writer.write(message + "\n");
                writer.flush();
                String response = reader.readLine();
                System.out.println("Message from server: " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

多个客户端连接聊天:

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

public class Server {
    // 存储所有连接到服务器的客户端
    private static List clients = new ArrayList<>();
    
    public static void main(String[] args) {
        try {
            // 创建ServerSocket对象,监听端口号为8888
            ServerSocket serverSocket = new ServerSocket(8888);
            
            System.out.println("Server is running...");
            
            // 不断接受客户端连接请求
            while (true) {
                // 等待客户端连接
                Socket socket = serverSocket.accept();
                System.out.println("Client connected.");
                
                // 添加新的客户端到列表中
                clients.add(socket);
                
                // 创建新线程处理该客户端的消息
                new Thread(new ServerHandler(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    // 处理客户端消息的线程
    static class ServerHandler implements Runnable {
        private Socket socket;
        
        public ServerHandler(Socket socket) {
            this.socket = socket;
        }
        
        public void run() {
            try {
                // 创建输入流和输出流
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();
                
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
                
                // 不断读取客户端发送的消息并广播
                while (true) {
                    String message = reader.readLine();
                    System.out.println("Message from client: " + message);
                    
                    // 广播消息给所有客户端
                    for (Socket client : clients) {
                        OutputStream os = client.getOutputStream();
                        os.write((message + "\n").getBytes());
                        os.flush();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

客户端代码与之前的代码相同,不需要做改变。

这个示例程序使用了多线程的方式,为每个连接到服务器的客户端创建一个新的线程来处理消息。每次有客户端发送消息,服务端会将消息广播给所有连接到服务器的客户端。

你可能感兴趣的:(粉丝栏,java,开发语言)