欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多线程-TCP通信

程序员文章站 2022-06-06 07:54:37
...
/**
 * 服务器端
 * @author Hui
 */

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class TcpServer {
    private static ArrayList<Socket> socketList = new ArrayList<>();
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(10086);
            System.out.println("等待客户端连接");
            while (true) {
                Socket socket = serverSocket.accept(); // 监听socket
                socketList.add(socket);
                new Thread(new ServerSendThread(socket, socketList)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 服务器发送接收线程
 * @author Hui
 */
class ServerSendThread implements Runnable {
    private Socket socket = null;
    private ArrayList<Socket> socketList = null;
    private OutputStreamWriter sendBackInfo;
    private PrintWriter sendInfo;

public ServerSendThread(Socket socket, ArrayList<Socket> socketList) {
    this.socket = socket;
    this.socketList = socketList;
}
public void run() {
    try {
        System.out.println(socket.getInetAddress().getHostAddress() + "进入聊天室");
        sendMsg("你已进入辉总的聊天室", socket);
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        BufferedWriter writer = new BufferedWriter(new FileWriter("d:/bbb/chatLog.txt", true)); // true表示追加
        // 读取数据内容
        writer.write(socket.getInetAddress().getHostAddress() + "\r\n");
        String line;
        while ((line = reader.readLine()) != null) {
            // 向所有客户端转发消息
            for (Socket socket : socketList) {
                sendMsg(line, socket);
            }
            // 服务器写入日志文件
            writer.append(line + "\r\n");
            writer.flush();
            // 打印客户端消息
    System.out.println(socket.getInetAddress().getHostAddress());
            System.out.println(line);
        }
        // 关闭资源
        writer.close(); // *
        sendBackInfo.close(); // *
    } catch (IOException e) {
        // 客户端断开线程时
        System.out.println(socket.getInetAddress().getHostAddress() + "断开了连接");
        socketList.remove(socket);
    }
}
// 服务器发送消息函数
public void sendMsg(String Msg, Socket socket) throws IOException {
    sendInfo = new PrintWriter(socket.getOutputStream(), true);
    sendInfo.println(Msg);
}
}

/**
 * 客户端
 * @author Hui
 */
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class TcpClient {
    public static void main(String[] args) {
        try {
            // 为客户端创建发送和接收线程
            Socket ClientSocket = new Socket("192.168.15.254", 10086);
            new Thread(new ClientSendThread(ClientSocket)).start();
            new Thread(new ClientReceiveThread(ClientSocket)).start();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
// 客户端发送线程
class ClientSendThread implements Runnable {
    private Socket ClientSocket = null;
    public ClientSendThread(Socket socket) {
        this.ClientSocket = socket;
    }
    public void run() {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            PrintWriter out = new PrintWriter(ClientSocket.getOutputStream(), true);
            // 发送
            String len;
            while ((len = reader.readLine()) != null) {
                out.println(len);
            }
            // 关闭资源
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// 客户端接收线程
class ClientReceiveThread implements Runnable {
    private Socket ClientSocket = null;
    public ClientReceiveThread(Socket socket) {
        this.ClientSocket = socket;
    }
    public void run() {
        // 接收反馈信息
        try {
            BufferedReader readBackInfo = new BufferedReader(new InputStreamReader(ClientSocket.getInputStream()));
            String backInfo;
            while ((backInfo = readBackInfo.readLine()) != null) { // 打印消息
                System.out.println(ClientSocket.getInetAddress().getHostAddress());
                System.out.println(backInfo);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}