import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class server extends Frame implements ActionListener
{
static server frm=new server();
int port;
DataInputStream dis=null;
DataOutputStream dos=null;
Label portLabel=new Label("port ");
Label space =new Label(" ");
TextField portText =new TextField(10);
Button link=new Button("link");
Label sayLabel=new Label("say");
TextField sayText=new TextField (60);
Button send =new Button("send");
TextArea info=new TextArea();
Panel p1=new Panel();
Panel p2=new Panel();
Panel p3=new Panel();
ServerSocket server;
Socket socket;
String strsay;
public static void main(String[] args)
{
frm.initView();
frm.linstener();
}
////////////界面设置
void initView()
{
frm.setSize(600,600);
frm.setLayout(new BorderLayout());
p2.setLayout(new BorderLayout());
p1.add(portLabel);
p1.add(portText);
p1.add(space);
p1.add(link);
p2.add(info);
p3.add(sayLabel);
p3.add(sayText);
p3.add(send);
frm.add(p1,BorderLayout.NORTH);
frm.add(p2,BorderLayout.CENTER);
frm.add(p3,BorderLayout.SOUTH);
frm.setVisible(true);
}
/////////链接网络
void connect()
{
try
{
System.out.println("进入connect函数");
server=new ServerSocket(port);
System.out.println("马上链接");
socket=server.accept();
dis=new DataInputStream(socket.getInputStream());
dos=new DataOutputStream(socket.getOutputStream());
System.out.println("连接成功");
// String str=dis.readUTF();
//info.append(str+"\n");
//进入线程
new Thread(new clientinfo()).start();
} catch (IOException e)
{
e.printStackTrace();
}
}
////////注册函数
void linstener()
{
this.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
String str=new String ("server will close");
try {
dos.writeUTF(str);
} catch (IOException e1)
{
e1.printStackTrace();
}
disconnect();
System.exit(0);
}});
link.addActionListener(frm);
send.addActionListener(frm);
sayText.addActionListener(frm);
}
/////////监听实现函数
@Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==link)
{
String str=portText.getText();
str.trim();
port=Integer.parseInt( str);
System.out.println(port);
frm.connect();
}
if(e.getSource()==sayText)
{
strsay=sayText.getText();
info.append(strsay+"\n");
sayText.setText("");
}
if(e.getSource()==send)
{
System.out.println("进入send函数");
try
{
dos.writeUTF(strsay);
dos.flush();
} catch (IOException e1)
{
e1.printStackTrace();
}
}
}
/////////设置线程函数
class clientinfo extends Thread
{
public void run()
{
while(true)
{
try
{
System.out.println("进入线程函数");
String str = dis.readUTF();
if(str.equals("client will close"))
{
dis.close();
break;
}
info.append(str+"\n");
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
void disconnect()
{
try {
if(dis!=null)
dis.close();
if(dos!=null)
dos.close();
socket.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}