package network06;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Sever {
public static void main(String[] args) {
new Sever().startup();
}
private void startup(){
ServerSocket ss =null;
Socket s= null;
try {
ss =new ServerSocket(5858);
while(true){
s =ss.accept();//来一个就创建一个Socket对象
SeverThread st = new SeverThread(s);//这两句无非是为了run()方法
new Thread(st).start(); //
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(ss!=null)ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class SeverThread implements Runnable{
private Socket s= null;
private BufferedReader br=null;
private PrintWriter pw = null;
private String name ;
private boolean flag =true;
public SeverThread(Socket s) throws IOException {
this.s =s;
br =new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream(),true);
name = s.getInetAddress().getHostAddress()+":"+s.getPort();
System.out.println(name+"已经连接上");
}
private void receive() throws IOException{
String str=null;
while((str=br.readLine())!=null){
if(str.equalsIgnoreCase("quite")){
stop();
//关闭,进行资源的释放
pw.println("close");
break;
}
System.out.println(name+"--"+str);
pw.println("Receive"+str);
}
System.out.println(name+"已经离开");
}
private void stop(){
flag=false;
}
public void run() {
try {
//while(true){
// if(!flag)break;
receive();
//}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(s!=null)s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
线程调用run()方法,这个外层循环结构,有什么作用?while((str=br.readLine())!=null)好像可以控制输入循环,就一直等着我们输入