熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java Socket 編程——多線程網絡聊天程序

2013-11-23 19:26:12  來源: Java核心技術 

  用java進行網絡編程確實很方便很容易上手這幾天用java進行socket編程收獲不少

  首先進行服務端的編程作為服務端編程主要按下面幾個步驟進行

  // 創建socket
    ServerSocket ss = new ServerSocket(PortNumber);
    Socket s = ssaccept(); //監聽器產生阻塞直到有連接才停止阻塞

  // 打開輸入流輸出流
    OutputStream os = sgetOutputStream();
    BufferedOutputStream bos = new BufferedOutputStream(os);
    InputStream is = sgetInputStream();

  // 根據一定的協議讀寫數據
    // 服務器 > 客戶
    //oswrite(HelloI am Server!getBytes());
    boswrite(HelloI am Server!getBytes());
    bosflush(); //注意!!

  // 服務器 < 客戶
    byte[] buf = new byte[];
    int len = isread(buf);
    Systemoutprintln(new String(buf len));

  // 關系流和Socket
    //osclose();
    bosclose();
    isclose();
    sclose();
    ssclose();

  作為客戶端則分為下面幾個步驟其實和服務端差不多只是少了用ServerSocket進行監聽

  // 創建socket
    Socket s = new Socket(InetAddressgetByName(localhost)
            PortNumber);
    // 打開輸入流輸出流
    OutputStream os = sgetOutputStream();
    InputStream is = sgetInputStream();

  // 根據一定的協議讀寫數據
    // 服務器 > 客戶
    byte[] buf = new byte[];
    int len = isread(buf);
    Systemoutprintln(new String(buf len));
    // 服務器 < 客戶
    oswrite(HelloI am Client!getBytes());

  // 關系流和Socket
    osclose();
    isclose();
    sclose();

  上面這些只是一個單線程的服務端>客戶端的程序只能進行一次通訊多次通訊將被告知無法連接

  這時我們就需要用到進程Thread進行編程將其改造成多線程聊天程序可以同時進行多客戶端的連接與發送信息

  代碼如下

  //Serverjava

  import javaawt*;
    import *;
    import javaio*;

  public class Server extends Thread {
        ServerSocket skt;

  Socket Client[]=new Socket[];;
        Socket Client=null;

  int i = ;

  TextArea in;

  int portk=l=;

  //BufferedReader theInputStream;

  PrintStream theOutputStream;

  //String readin;

  Face chat;

  public Server(int port Face chat) {
            try {
                thisport = port;
                skt = new ServerSocket(port);
                thischat = chat;
            } catch (IOException e) {
                chattaappend(etoString());
            }
        }

  public void run() {

  chattaappend(等待連線);

  while (true) {
                //Systemoutprint(+i+\n);
                try {

  Client[k] = sktaccept(); /* 接收客戶連接 */

  //當有客戶端連接時就新建一個子線程

  if (i < ) {
                    ServerThread server[] = new ServerThread[];
                     server[k]= new ServerThread(Client[k] thischat i);
                     l=serverlength;
                     server[k]start();
                    chattaappend(客戶端 + Client[k]getInetAddress() + 已連線\n);
                    /*theInputStream = new BufferedReader(new InputStreamReader(Client
                            getInputStream()));*/
                    //for(int j=;j<serverlength;j++)
                    theOutputStream = new PrintStream(server[k]getClient()getOutputStream());
                    i = server[k]getI();
                    k++;
                } else {
                    //theOutputStream = new PrintStream(null);
                }

  } catch (SocketException e) {
                //chattaappend(連線中斷!\n);

  //chatclientBtnsetEnabled(true);
                //chatserverBtnsetEnabled(true);
                //chattfaddresssetEnabled(true);
                //chattfportsetEnabled(true);
                //try {

  //sktclose();
                        //Clientclose();
                    //} catch (IOException err) {
                    //    chattaappend(errtoString());
                    //}
                } catch (IOException e) {
                    chattaappend(etoString());
                }
            }

  }

  public void dataout(String data) {
            //for(int j=;j<l;j++)
            theOutputStreamprintln(data);
        }
    }

  class ServerThread extends Thread {
        ServerSocket skt;

  Socket Client;

  TextArea in;

  int port;

  int i;

  BufferedReader theInputStream;

  PrintStream theOutputStream;

  String readin;

  Face chat;


    //服務端子線程

  public ServerThread(Socket s Face chat int i) {
            thisi = ++i;
            Client = s;
            //thisport = port;
            //skt = new ServerSocket(port);
            thischat = chat;

  }

  public int getI() {
            return thisi;
        }
        public Socket getClient() {
            return thisClient;
        }
        public void run() {

  //chattaappend(等待連線);

  try {
                //Client = sktaccept(); /* 接收客戶連接 */

  //chattaappend(客戶端 + ClientgetInetAddress() + 已連線\n);
                theInputStream = new BufferedReader(new InputStreamReader(Client
                        getInputStream()));
                theOutputStream = new PrintStream(ClientgetOutputStream());

  while (true) {
                    readin = theInputStreamreadLine();
                    chattaappend(readin + \n);
                }

  } catch (SocketException e) {
                chattaappend(連線中斷!\n);

  chatclientBtnsetEnabled(true);
                chatserverBtnsetEnabled(true);
                chattfaddresssetEnabled(true);
                chattfportsetEnabled(true);
                try {
                    i;
                    sktclose();
                    Clientclose();
                } catch (IOException err) {
                    chattaappend(errtoString());
                }
            } catch (IOException e) {
                chattaappend(etoString());
            }
        }

  public void dataout(String data) {
            theOutputStreamprintln(data);
        }
    }

  //Clientjava

  import *;
    import javaio*;
    import javaxswingTimer;
    class Client extends Thread {
        Socket skt;
        InetAddress host;
        int port;

  BufferedReader theInputStream;
        PrintStream theOutputStream;
        String readin;

  Face chat;

  public Client(String ip int p Face chat) {
            try {
                host = InetAddressgetByName(ip);
                port = p;
                thischat = chat;
            } catch (IOException e) {
                chattaappend(etoString());
            }
        }

  public void run() {
            try {
                chattaappend(嘗試連線);

  skt = new Socket(host port);
                chattaappend(連線成功\n);

  theInputStream = new BufferedReader(new InputStreamReader(skt
                        getInputStream()));

  theOutputStream = new PrintStream(sktgetOutputStream());
                //Timer myTimer = new Timer();
                while (true) {
                    readin = theInputStreamreadLine();
                    chattaappend(readin + \n);
                }
            } catch (SocketException e) {
                chattaappend(連線中斷!\n);
                chatclientBtnsetEnabled(true);
                chatserverBtnsetEnabled(true);
                chattfaddresssetEnabled(true);
                chattfportsetEnabled(true);
                try {
                    sktclose();
                } catch (IOException err) {
                    chattaappend(errtoString());
                }
            } catch (IOException e) {
                chattaappend(etoString());
            }
        }

  public void dataout(String data) {
            theOutputStreamprintln(data);
        }
    }

  //軟件界面進行按鍵監聽調用

  //facejava

  import javaawt*;
    import javaawtevent*;

  public class Face extends Frame {
        /**
         *
         */
        private static final long serialVersionUID = L;
        Button clientBtn serverBtn;
        TextArea ta;
        TextField tfaddress tfport tftype;
        int port;
        Client client;
        Server server;
        boolean iamserver;
        static Face frm;

  public Face() {
            clientBtn = new Button(客戶端);
            serverBtn = new Button(服務器);
            ta = new TextArea( TextAreaSCROLLBARS_BOTH);
            tfaddress = new TextField( );
            tfport = new TextField();
            tftype = new TextField();

  tftypeaddKeyListener(new TFListener());
            tasetEditable(false);

  setLayout(new FlowLayout());
            add(tfaddress);
            add(tfport);
            add(clientBtn);
            add(serverBtn);
            add(ta);
            add(tftype);
            setSize( );
            setTitle(我的聊天室);
            thissetVisible(true);

  clientBtnaddActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {

  port = IntegerparseInt(tfportgetText());

  client = new Client(tfaddressgetText() port frm);

  clientstart();

  tfaddresssetEnabled(false);
                    tfportsetEnabled(false);
                    serverBtnsetEnabled(false);
                    clientBtnsetEnabled(false);
                }
            });

  serverBtnaddActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {

  port = IntegerparseInt(tfportgetText());

  server = new Server(port frm);

  serverstart();

  iamserver = true;
                    tfaddresssetText(成為服務器);

  tfaddresssetEnabled(false);
                    tfportsetEnabled(false);
                    serverBtnsetEnabled(false);
                    clientBtnsetEnabled(false);
                }
            });

  addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    Systemexit();
                }
            });

  }

  public static void main(String args[]) {
            frm = new Face();
        }

  private class TFListener implements KeyListener {
            public void keyPressed(KeyEvent e) {

  if (egetKeyCode() == KeyEventVK_ENTER) {

  taappend(> + tftypegetText() + \n);

  if (iamserver)
                        serverdataout(tftypegetText());
                    else
                        clientdataout(tftypegetText());

  tftypesetText();
                }
            }

  public void keyTyped(KeyEvent e) {
            }

  public void keyReleased(KeyEvent e) {
            }
        }
    }

  這個程序我限制了連接數大家可以根據自己的需要進行修改


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26868.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.