服务器端:
public class Server {
private int port=8821;
private ServerSocket serverSocket;
private ExecutorService executorService;//线程池
private final int POOL_SIZE=10;//单个CPU线程池大小
public MultiThreadServer()throws IOException{
serverSocket=new ServerSocket(port);
//Runtime的availableProcessor()方法返回当前系统的CPU数目.
executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE);
System.out.println("服务器启动!");
}
public void service(){
while(true){
Socket socket=null;
try {
//接收客户连接,只要客户进行了连接,就会触发accept();建立连接!
socket=serverSocket.accept();
executorService.execute(new ServerConThread(socket));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args)throws IOException {
new Server().service();
}
}
线程:
public class ServerConThread implements Runnable{
private PrintWriter pw =null;
private BufferedReader br=null;
private Socket socket;
public ServerConThread(Socket socket){
this.socket=socket;
}
private PrintWriter getWriter(Socket socket)throws IOException{
OutputStream socketOut=socket.getOutputStream();
return new PrintWriter(socketOut,true);
}
private BufferedReader getReader(Socket socket)throws IOException{
InputStream socketIn=socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn));
}
public void run(){
try {
System.out.println("新的连接: "+socket.getInetAddress()+":"+socket.getPort());
br=getReader(socket);
pw=getWriter(socket);
String msg=null;
while((msg=br.readLine())!=null){
System.out.println("客户端说:"msg);
pw.println("我是服务器!");
}
br.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("输入输出流异常!");
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("输入输出流异常!);
}
}
}
}
客户端:
public class Client {
public static void main(String[] args) {
int numTasks = 10;
ExecutorService exec = Executors.newCachedThreadPool();
for(int i=0;i<10;i++){
exec.execute(createTask(i));
}
}
// 定义了一个简单的任务
private static Runnable createTask(final int taskID) {
return new Runnable() {
private Socket socket =null;
private int port=6666;
public void run() {
System.out.println("任务 " + taskID +":开始");
try {
socket = new Socket("localhost", port);
OutputStream socketOut = socket.getOutputStream();
PrintWriter pw = new PrintWriter(socketOut);
pw.println("我是客户端!");
pw.flush();
// 接收服务器的反馈
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String msg = null;
while ((msg = br.readLine()) !=null)
System.out.println(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/quzhiyu_rjgcs/article/details/48085873