import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class Server1 extends WindowAdapter implements ActionListener{
ServerSocket server;
Socket client;
boolean flag;
BufferedReader cin;
PrintWriter cout;
Frame f;
Button bl;
TextArea ta;
TextField tf;
public Server1(){
try{
server=new ServerSocket(8888);
this.ChatFrame(" 服务器 端口号:"+server.getLocalPort());
flag=true;
while(flag){
client=server.accept();
System.out.println("已建立连接");
InputStream is=client.getInputStream();
cin=new BufferedReader(new InputStreamReader(is));
OutputStream os=client.getOutputStream();
cout=new PrintWriter(os,true);
String aline;
while((aline=cin.readLine())!=null){
ta.append("杨桐: "+aline+"\n");
if(aline.equals("bye")){
flag=false;
break;
}
}
is.close();
cin.close();
os.close();
cout.close();
client.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public void ChatFrame(String str) {
f=new Frame("双人聊天程序"+str);
f.setSize(350,500);
ta=new TextArea();
f.add(ta);
ta.setEditable(false);
Panel p=new Panel();
f.add(p,"South");
tf=new TextField(20);
bl=new Button("发送");
p.add(tf);
p.add(bl);
bl.addActionListener(this);
tf.addActionListener(this);
f.setVisible(true);
f.addWindowListener(this);
}
public void actionPerformed(ActionEvent e){
ta.append("张晓枫: "+tf.getText()+"\n");
cout.println(tf.getText());
tf.setText("");
}
public void windowClosing(WindowEvent e){
cout.println("bye");
System.exit(0);
}
public static void main(String args[]){
new Server1();
}
}