Java Socket驅(qū)動(dòng)關(guān)鍵代碼經(jīng)典剖析
Java Socket驅(qū)動(dòng)如何才能變得***?其實(shí)只要掌握好相關(guān)的代碼就可以把相關(guān)的一起搞定,下面我們就看看在Java Socket驅(qū)動(dòng)中的關(guān)鍵代碼,希望大家有所收獲。那么我們首先來(lái)看看各種接口上的知識(shí)。
由于是基于事件Java Socket驅(qū)動(dòng)的組件,所以MySingleThreadServer1類(lèi)要繼承ActionListener接口,實(shí)現(xiàn)該接口唯一的方法actionPerformed(ActionEvent e),即當(dāng)觸發(fā)某一事件時(shí),執(zhí)行該方法內(nèi)的代碼。關(guān)鍵代碼如下:
- public class MySingleThreadServer1 implements
ActionListener{- private Frame f;
- private TextArea ta1 = newTextArea("",5,40,TextArea.
SCROLLBARS_VERTICAL_ONLY);- private TextArea ta2 = new TextArea("",16,52,TextArea.
SCROLLBARS_VERTICAL_ONLY);- private Button b;
- private String msg ="";
- OutputStream os;
- DataOutputStream dos;
- InputStream is;
- DataInputStream dis;
- ServerSocket ss;
- Socket s;
- public MySingleThreadServer1(){
- f = new Frame("server:小馬");
- b = new Button("服務(wù)器發(fā)送");
- f.setBackground(Color.WHITE);
- b.setBackground(Color.LIGHT_GRAY);
- ta1.setBackground(Color.LIGHT_GRAY);
- ta2.setBackground(Color.LIGHT_GRAY);
- ta2.setEditable(false); //set to only be read
- f.setLayout(new FlowLayout(FlowLayout.LEFT));
- f.add(ta1);
- f.add(b);
- f.add(ta2);
- f.setLocation(200,200);
- f.setSize(400,400);
- f.setResizable(false);
- f.setVisible(true);
- b.addActionListener(this);
- f.addWindowListener(new WindowAdapter(){
- public void windowClosing(WindowEvent e){
- System.exit(0);
- }
- });
- try{
- ss = new ServerSocket(7777);
- s = ss.accept();
- is = s.getInputStream();
- dis = new DataInputStream(is);
- os = s.getOutputStream();
- dos = new DataOutputStream(os);
- serverReadSome(); //接受客戶端發(fā)來(lái)的信息
- }catch(IOException e){
- e.printStackTrace();
- }
- }
- public void actionPerformed(ActionEvent e){
//服務(wù)器點(diǎn)擊按鈕觸發(fā)時(shí)間- try{
- msg = ta1.getText();
- dos.writeUTF(msg);
- ta2.append("小馬:"+msg+"\n");
- ta1.setText("");
- ta1.requestFocus();
- }catch(IOException ioe){
- ioe.printStackTrace();
- }
- }
- public void serverReadSome(){
- try{
- while(true){
- msg = dis.readUTF();
- ta2.append("小徐:"+msg+"\n");
- }
- }catch(IOException ioe){
- ioe.printStackTrace();
- }
- }
- public static void main(String args[]){
- new MySingleThreadServer1();
- }
- }
我把GUI的初始化信息和事件驅(qū)動(dòng)的信息放到了MySingleThreadServer1的構(gòu)造函數(shù)中,使之new一個(gè)的時(shí)候就初始化該類(lèi)。以上就是對(duì)Java Socket驅(qū)動(dòng)的詳細(xì)介紹。希望大家有所收獲。
【編輯推薦】