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

Java多线程实现C/S多客户端通信

程序员文章站 2024-03-22 23:22:28
...

功能描述

  • 架设服务器和客户端,在客户端发送圆半径到服务器,从服务器中获得圆面积。
  • 在服务器中放计算面积类,客户端中只有连接服务器以及发送。
  • 可开启多个客户端连接服务器

源码

MultiServer.java


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MultiServer {
	public static void main(String[] args) throws IOException {
		int clientNo = 1;
		ServerSocket serverSocket = new ServerSocket(8081);
		// 创建线程执行器
		ExecutorService executor = Executors.newCachedThreadPool();
		try {
			System.out.println("服务器程序启动,开始接收客户请求");
			while (true) {
				Socket socket = serverSocket.accept();
				InetAddress clientAddress = socket.getInetAddress();
				System.out.println("客户" + clientNo + " 的主机名是" + clientAddress.getHostName());
				System.out.println("客户" + clientNo + " 的IP地址是" + clientAddress.getHostAddress());
				// 将任务添加到执行器中
				executor.execute(new ComputeArea(socket, clientNo));
				clientNo++;
			}
		} finally {
			serverSocket.close();
		}
	}
}

class ComputeArea implements Runnable {
	private Socket socket;
	private int clientNo;

	public ComputeArea(Socket socket, int clientNo) {
		this.socket = socket;
		this.clientNo = clientNo;
	}

	@Override
	public void run() {
		try {
			DataInputStream isFromClient = new DataInputStream(socket.getInputStream());
			DataOutputStream osToClient = new DataOutputStream(socket.getOutputStream());
			while (true) {
				double radius = isFromClient.readDouble();
				System.out.println("从客户端接收的半径值:" + radius);
				double area = radius * radius * Math.PI;
				osToClient.writeDouble(area);
				osToClient.flush();
			}
		} catch (IOException e) {
			System.err.println(e);
		}

	}

}

Client.java


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

public class Client {
	public static void main(String[] args) {
		try (Socket socket = new Socket("localhost", 8081);
				DataInputStream isFromServer = new DataInputStream(socket.getInputStream());
				DataOutputStream osToServer = new DataOutputStream(socket.getOutputStream());
				Scanner sc = new Scanner(System.in);) {
			while (true) {
				System.out.print("请输入圆半径值:");
				double radius = sc.nextDouble();
				osToServer.writeDouble(radius);
				osToServer.flush();
				double area = isFromServer.readDouble();
				System.out.println("圆的面积是:" + area);
			}
		} catch (IOException e) {
			System.err.println(e);
		}
	}
}

相关标签: Java