为什么用while(true)语句? 急,急,急!
请帮忙看一下,网络编程的一个服务器端,我不懂为什么要用While(true)语句,那什么时候跳出循环体亚?而我试过,如果屏蔽这条语句,机器将会出奇的慢,可能进入了死循环,请大家帮忙看一下好么?非常感谢!
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class Server extends Frame implements ActionListener{
Label label=new Label("chanter");
Panel panel=new Panel();
TextArea ta=new TextArea();
TextField tf=new TextField(10);
ServerSocket server;
Socket client;
InputStream in;
OutputStream out;
public Server(){
super("server");
setSize(250,250);
panel.add(label);
panel.add(tf);
tf.addActionListener(this);
add("North",panel);
add("Center",ta);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);}});
show();
try{
server=new ServerSocket(2000);
client=server.accept();
ta.append("connected host:"+client.getInetAddress().getHostName()+"\n\n");
in=client.getInputStream();
out=client.getOutputStream();
}
catch(IOException e){}
while(true){
try{
byte[] buf=new byte[256];
in.read(buf);
String str=new String(buf);
ta.append("guest:"+str);
ta.append("\n");
}
catch(IOException e){}
}
}
public void actionPerformed(ActionEvent e){
try{
String str=tf.getText();
byte[] buf=str.getBytes();
tf.setText(null);
out.write(buf);
ta.append("I say:"+str);
ta.append("\n");
}catch(IOException ioe){
}
}
public static void main(String args[]){
new Server();}
}
客户端:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class Client extends Frame implements ActionListener{
Label label=new Label("chanter");
Panel panel=new Panel();
TextArea ta=new TextArea();
TextField tf=new TextField(10);
Socket client;
InputStream in;
OutputStream out;
public Client(){
super("Client");
setSize(250,250);
panel.add(label);
panel.add(tf);
tf.addActionListener(this);
add("North",panel);
add("Center",ta);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);}});
show();
try{
client=new Socket(InetAddress.getLocalHost(),2000);
ta.append("connected Server:"+client.getInetAddress().getHostName()+"\n\n");
in=client.getInputStream();
out=client.getOutputStream();
}
catch(IOException e){}
//while(true){
try{
byte[] buf=new byte[256];
in.read(buf);
String str=new String(buf);
ta.append("Server syes:"+str);
ta.append("\n");
}
catch(IOException e){}
// }
}
public void actionPerformed(ActionEvent e){
try{
String str=tf.getText();
byte[] buf=str.getBytes();
tf.setText(null);
out.write(buf);
ta.append("I say:"+str);
ta.append("\n");
}catch(IOException ioe){
}
}
public static void main(String args[]){
new Client();}
}