站长www.software8.co

热转印www.heatpress123.net

Socket 多线程,Java C/S 模式 编程(客户端)

[java] view plaincopyprint? // Fig. 18.5: Client.java // Client that reads and displays information sent from a Server. import java.awt.event.*; import java.awt.*; import javax.swing.*; @SuppressWarnings("serial") public class ClientGUI extends JFrame { private JTextArea displayArea; private JTextField enterField; private String request=""; public ClientGUI() { super( "Client" ); Container container = getContentPane(); displayArea = new JTextArea(); enterField=new JTextField(); container.add(enterField,BorderLayout.NORTH); container.add( new JScrollPane( displayArea ), BorderLayout.CENTER ); setSize( 300, 150 ); setAlwaysOnTop(true); setVisible( true ); Handler handler=new Handler(); enterField.addActionListener(handler); } private class Handler implements ActionListener { public void actionPerformed(ActionEvent e) { setRequest(e.getActionCommand()); setField(""); } } public JTextField getGUIField() { return enterField; } public JTextArea getGUIArea() { return displayArea; } public void setRequest(String s) { request=s; } public String getRequest() { return request; } public void setField(String s) { enterField.setText(s); } public void appendArea(String s) { displayArea.append(s+"\n"); } public void setArea(String s) { displayArea.setText(s); } } // end class Client import java.io.*; import java.net.*; public class Client extends Thread { private ClientGUI g; private String time=""; private Socket client; private ObjectInputStream in; private ObjectOutputStream out; public Client( ClientGUI gui) { super( "Client" ); g=gui; g.setRequest("get"); } public void run() { try { Thread.sleep(500); client = new Socket( InetAddress.getLocalHost(), 24680 ); out=new ObjectOutputStream(client.getOutputStream()); in=new ObjectInputStream(client.getInputStream()); Thread.sleep(500); while(true) { Thread.sleep(500); if(!g.getRequest().equals("")) { out.writeObject(g.getRequest()); out.flush(); Thread.sleep(500); if(g.getRequest().equals("get")) { time=in.readObject().toString(); g.setArea(time); } else if(g.getRequest().equals("close")) { out.close(); in.close(); client.close(); } else continue; } } } catch ( IOException ioException ) { ioException.printStackTrace(); } catch(InterruptedException e) { } catch (ClassNotFoundException e) { e.printStackTrace(); } } } // end class Client // Fig. 18.5: Client.java // Client that reads and displays information sent from a Server. import javax.swing.*; public class ClientRun { //private String request; public static void main( String args[] ) { ClientGUI app; app = new ClientGUI( ); app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); Client client=new Client(app); client.start(); } } // end class Client

posted on 2012-09-24 07:43 文哥哥 阅读(1356) 评论(0)  编辑  收藏

<2012年9月>
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

导航

统计

常用链接

留言簿

随笔档案

文章档案

友情链接

最新随笔

搜索

最新评论

阅读排行榜

评论排行榜