import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
class Server implements WindowListener,ActionListener
{
Frame f;
Label lb1;
Label lb2;
TextArea ta;
TextField tf;
Button bt;
ServerSocket server;
Socket clientSocket;
InputStream is;
OutputStream os;
DataInputStream sin;
DataOutputStream sout;
String str1;//向客户机发送的str
String str2;//收到客户机的str
boolean flag=false;
public static void main(String[] args)
{
Server server=new Server();
server.creatwindow();
server.serverStart();
}
void creatwindow()
{
f=new Frame("server");
lb1=new Label("对话框");
lb2=new Label("发送消息");
ta=new TextArea(10,55);
tf=new TextField(55);
bt=new Button("发送");
f.add(lb1);
f.add(ta);
f.add(lb2);
f.add(tf);
f.add(bt);
f.addWindowListener(this);
bt.addActionListener(this);
f.setLayout(new FlowLayout());
f.setSize(500,300);
f.setVisible(true);
f.setLocation(100,500);
}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void windowClosed(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowActivated(WindowEvent e){}
void serverStart()
{
try
{
server=new ServerSocket(2000);
ta.setText("服务已启动\n"+"等待链接请求... ...\n");
while(true)
{
clientSocket=server.accept();
ta.append("链接已成功建立\n");
getResponse();
if(flag) //如果客户端/服务器端发送bye则关闭所有的链接
{
sout.close();
sin.close();
clientSocket.close();
ta.append("链接已中断");
break;
}
}
}
catch(Exception e)
{
ta.setText("发生错误请立即退出");
}
}
void sendRequest()
{
try{
os=clientSocket.getOutputStream();
sout=new DataOutputStream(os);
sout.writeUTF(str1);
}
catch(IOException e)
{
ta.append("IO错误\n");
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==bt)
{
str1=tf.getText();
tf.setText("");
ta.append("服务器说:"+str1+"\n");
if(str1.equals("bye"))
{
flag=true;
}
}
sendRequest();
}
void getResponse()
{
try{
is=clientSocket.getInputStream();
sin=new DataInputStream(is);
while((str2=sin.readUTF())!=null)
{
ta.append("客户机说:"+str2+"\n");
if(str2.equals("bye"))
{
flag=true;
}
}
}
catch(IOException e)
{
ta.append("IO错误\n");
}
}
}