QQServer.java //axun @copy right package axun.com; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class QQServer{ private JFrame f=new JFrame("QQ服务器端"); private JPanel pleft=new JPanel(new BorderLayout()); private JPanel pright=new JPanel(); private List list=new List(); private TextArea t1=new TextArea(); private TextArea t2=new TextArea(); private Button b=new Button("发送"); //一下是 网络通信用的变量 DataOutputStream dos=null; BufferedReader br=null; DataInputStream dis=null; public QQServer(){ f.setSize(400,300); f.setLayout(new BorderLayout()); f.add(pleft,BorderLayout.WEST); f.add(pright,BorderLayout.CENTER); pleft.add(list); pright.setLayout(new GridLayout(3,1)); pright.add(t1); pright.add(t2); pright.add(b); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); b.addActionListener(new bListener()); } public void Addt1(String s){ t1.append(s); } public void addList(String s){ list.addItem(s); } public static void main(String[] args) throws Exception{ QQServer server=new QQServer(); InputStream in=null; OutputStream out=null; String string=null; ServerSocket ss=new ServerSocket(4545); Socket s=null; s=ss.accept(); server.addList(s.toString()); in=s.getInputStream(); out=s.getOutputStream(); server.dis=new DataInputStream(in); server.dos=new DataOutputStream(out); Listen1 l=new Listen1(server,server.dis); Thread t=new Thread(l); t.start(); } class bListener implements ActionListener{ public void actionPerformed(ActionEvent e) { try{ dos.writeUTF(t2.getText()); Addt1("发送:"+"/n"); Addt1(" "+t2.getText()+"/n"); t2.setText(""); }catch(Exception ep){ Addt1("消息发送失败!/n"); } } } } class Listen1 implements Runnable{ private QQServer server=null; private DataInputStream dis=null; private String s=null; Listen1(QQServer server,DataInputStream dis){ this.server=server; this.dis=dis; } public void run() { // TODO Auto-generated method stub try{ while(true){ s=dis.readUTF(); server.Addt1("收到:"+"/n"); server.Addt1(" "+s+"/n"); } }catch(Exception e){ server.Addt1("Error!:"+s+"/n"); } } } |