一.单线程
服务端线程类
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
public class BSServerThread extends Thread{
private Socket soc;
public BSServerThread(Socket soc) {
this.soc = soc;
}
@Override
public void run() {
try {
PrintStream ps = new PrintStream(soc.getOutputStream());
ps.println("HTTP/1.1 200 OK");
ps.println("Content-Type:text/html;charset=UTF-8");
ps.println();
ps.println(" We Are The Champion ");
ps.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端类
import java.net.ServerSocket;
import java.net.Socket;
public class BSServerDemo1 {
public static void main(String[] args) {
System.out.println("=====HTTP Server Started=====");
try {
ServerSocket ss = new ServerSocket(8080);
while (true){
Socket soc = ss.accept();
//ss的accept方法返回一个套接字对象,等到了对方request,就在本地生成一个socket对应
System.out.println(soc.getRemoteSocketAddress()+" he came~~~");
new BSServerThread(soc).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
文章目录
线程池多网页访问
Runnable类
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
public class BSServerRunnable implements Runnable{
private Socket soc;
public BSServerRunnable(Socket soc) {
this.soc = soc;
}
@Override
public void run() {
try {
PrintStream ps = new PrintStream(soc.getOutputStream());
ps.println("HTTP/1.1 200 OK");
ps.println("Content-Type:text/html;charset=UTF-8");
ps.println();
ps.println(" We Are The Champion ");
ps.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端类
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;
public class BSServerDemo2 {
private static ExecutorService pool = new ThreadPoolExecutor(10,20,100, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
public static void main(String[] args) {
System.out.println("=====HTTP Server Started=====");
try {
ServerSocket ss = new ServerSocket(8080);
while (true){
Socket soc = ss.accept();
pool.execute(new BSServerRunnable(soc));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
单线程或多线程代码运行开始后,浏览器输入127.0.0.1:8080
效果如图



