在这个实例中我们假设自己的电脑是一台服务器,当外部有设备访问本机的1234端口(这里是localhost:1234)的时候,就相当于建立了一个连接,accept函数返回一个Socket.
所以很多设备访问主机的1234端口时,它们就相当于一个一个独立的线程,来访问服务器,执行各自的任务。
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main implements Runnable {
Socket csocket;
Main(Socket csocket){
this.csocket=csocket;
}
public static void main(String[] args) throws Exception{
ServerSocket ssock=new ServerSocket(1234);
System.out.println("Listening");
while (true) {
Socket sock=ssock.accept();
System.out.println("Connected");
new Thread(new Main(sock)).start();
}
}
@Override
public void run() {
try {
PrintStream pstream;
pstream = new PrintStream(csocket.getOutputStream());
for(int i=100;i>=0;i--){
pstream.println(i+" bottles of beer on the wall");
}
pstream.close();
csocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行解果:
Listening
Connected //这其实是在浏览器窗口中输入http://127.0.0.1:1234之后就显示连接
浏览器显示的内容如下: