日期:2014-05-20 浏览次数:20821 次
//服务器端 import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.net.*; import java.util.*; public class Server extends JFrame{ JTextArea txt; ServerSocket seSocket=null; public void serve(){ txt=new JTextArea(); this.setTitle("学习通讯类"); this.setLayout(new BorderLayout()); this.add(txt,BorderLayout.CENTER); this.setSize(500,300); this.setVisible(true); try{ seSocket=new ServerSocket(8000); txt.append("服务器启动时间是:"+new Date()+'\n'); } catch (BindException e) { System.out.println("端口使用中...."); System.out.println("请关掉相关程序并重新运行服务器!"); System.exit(0); } catch (IOException e) {} try{ while(true){ Socket st=seSocket.accept(); CtThread ct=new CtThread(); ct.deliveSt(st); new Thread(ct).start(); } }catch(IOException e){} } class CtThread implements Runnable{ Socket st=null; DataInputStream in=null; public void deliveSt(Socket st) { this.st=st; try{ in=new DataInputStream(st.getInputStream()); }catch(IOException e){} } public void run() { try{ BufferedReader br=new BufferedReader(new InputStreamReader(in)); while(true){ String Dialog=br.readLine(); txt.append("从客户端收到信息"+Dialog+'\n'); } }catch(IOException e){} } } public static void main(String args[]) { Server myserver=new Server(); myserver.serve(); } } //客户端类 import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.net.*; import java.util.*; public class Client extends JFrame implements ActionListener { JTextArea txta; JTextField txtf; JPanel pl; JButton bt; DataOutputStream out=null; Socket sc=null; PrintStream ps; Container f=this.getContentPane(); public void client() { f.setLayout(new BorderLayout()); txta=new JTextArea(); f.add(txta,BorderLayout.CENTER); txtf=new JTextField(20); bt=new JButton("发送"); pl=new JPanel(); pl.setLayout(new FlowLayout()); pl.add(txtf); pl.add(bt); bt.addActionListener(this); txtf.addActionListener(this); f.add(pl,BorderLayout.SOUTH); setTitle("信息发送端"); setSize(500,300); setVisible(true); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { disconnect(); System.exit(0); } }); try { Socket sc=new Socket("192.168.0.25",8000); out=new DataOutputStream(sc.getOutputStream()); ps=new PrintStream(out); } catch(IOException ex) { txta.append(ex.toString()+'\n'); } } public void actionPerformed(ActionEvent e) { if(e.getSource()==bt|e.getSource()==txtf) { String Dialog=txtf.getText(); try { ps.println(Dialog); txta.append("已经发送对话:"+Dialog+'\n'); txtf.setText(""); } catch(Exception ex) { txta.append(ex.toString()+'\n'); } } } public void disconnect() { try { out.close(); sc.close(); } catch (IOException e) {} } public static void main(String args[]) { Client myclient=new Client(); myclient.client(); } }