Cyh的博客

          Email:kissyan4916@163.com
          posts - 26, comments - 19, trackbacks - 0, articles - 220

          網絡編程>>基本的Socket編程

          Posted on 2009-12-12 16:04 啥都寫點 閱讀(229) 評論(0)  編輯  收藏 所屬分類: J2SE
                Socket 服務器端需要在某個端口上開啟服務端類型的Socket,即java.net.ServerSocket.通過它的accept方法等待并接收客戶端的請求,返回的是一個java.net.Socket對象,如果一直沒有客戶端請求,那么accept方法將會一直等待。
                Socket 客戶端根據服務器端的IP地址和端口號創建一個Socket對象,連接服務器。
                服務器端和客戶端都持有一個Socket對象,服務器端的Socket從服務器端指向客戶端,而客戶端的Socket從客戶端指向服務器端,就像在服務器和客戶端建立了兩條單向的管道
                Socket 類提供的getOutputStream方法獲得Socket的輸出流,getInputStream方法獲得Socket的輸入流。

          /**---------------------------SimpleServer.java-------------------------------*/



          /**
           * 一個簡單的socket服務器,能接受客戶端請求,并將請求返回給客戶端
           
          */

          public class SimpleServer {
              
          // 服務端偵聽的Socket
              ServerSocket serverSkt = null;
              
          // 客戶端
              Socket clientSkt = null;

              
          // 客戶端輸入流
              BufferedReader in = null;
              
          // 客戶端輸出流
              PrintStream out = null;

              
          // 構造方法
              public SimpleServer(int port){
                  System.out.println(
          "服務器代理正在監聽,端口:" + port);
                  
          try {
                      
          // 創建監聽socket
                      serverSkt = new ServerSocket(port);
                  }
           catch (IOException e) {
                      System.out.println(
          "監聽端口" + port + "失敗");
                  }

                  
          try {
                      
          // 接收連接請求
                      clientSkt = serverSkt.accept();
                  }
           catch (IOException e) {
                      System.out.println(
          "連接失敗");
                  }

                  
          try {
                      
          // 獲得輸出輸出流
                      in = new BufferedReader(new InputStreamReader(clientSkt
                              .getInputStream()));
                      out 
          = new PrintStream(clientSkt.getOutputStream());
                  }
           catch (IOException e) {
                  }

              }


              
          // 收到客戶端請求
              public String getRequest() {
                  String frmClt 
          = null;
                  
          try {
                      
          // 從客戶端的輸入流中讀取一行數據
                      frmClt = in.readLine();
                      System.out.println(
          "Server 收到請求:" + frmClt);
                  }
           catch (Exception e) {
                      System.out.println(
          "無法讀取端口..");
                      System.exit(
          0);
                  }

                  
          return frmClt;
              }


              
          // 發送響應給客戶端
              public void sendResponse(String response) {
                  
          try {
                      
          // 往客戶端輸出流中寫數據
                      out.println(response);
                      System.out.println(
          "Server 響應請求:" + response);
                  }
           catch (Exception e) {
                      System.out.println(
          "寫端口失敗");
                      System.exit(
          0);
                  }

              }


              
          public static void main(String[] args) throws IOException {
                  
          // 啟動服務器
                  SimpleServer sa = new SimpleServer(8888);
                  
          while (true{
                      
          // 讀取客戶端的輸入并返回給客戶端。
                      sa.sendResponse(sa.getRequest());
                  }

              }


          }

          /**--------------------------SimpleClient.java--------------------------*/

          /**
           * 一個簡單的socket客戶端,能夠往服務器發送socket請求。
           
          */

          public class SimpleClient {
              
              
          // 客戶端輸入輸出流
              PrintStream out;
              BufferedReader in;

              
          // 構造方法
              public SimpleClient(String serverName, int port) {
                  
          try {
                      
          // 根據服務器名和端口號,連接服務器
                      Socket clientSocket = new Socket(serverName, port); 
                      
          // 獲取socket的輸入輸出流
                      out = new PrintStream(clientSocket.getOutputStream());
                      in 
          = new BufferedReader(new InputStreamReader(clientSocket
                              .getInputStream()));
                  }
           catch (Exception e) {
                      System.out.println(
          "無法連接服務器!");
                  }

              }


              
          // 發送請求
              public void sendRequest(String request) {
                  
          // 向socket的輸出流寫數據
                  out.println(request); 
                  System.out.println(
          "Client 發送請求: " + request);
              }


              
          public String getResponse() {
                  String str 
          = new String();
                  
          try {
                      
          // 從socket的輸入流中讀取數據
                      str = in.readLine();
                      System.out.println(
          "Client收到Server返回: " + str);
                  }
           catch (IOException e) {
                  }
           
                  
          return str;
              }

          }





          /**-----------------------------ClientFrame.java---------------------------------------*/

          /**
           * 客戶端的圖形界面
           
          */

          public class ClientFrame extends JFrame implements ActionListener {
              
          // "發送"按鈕
              JButton sendButton; 
              
          // 發送內容的輸入框
              JTextField inputField; 
              
          // 服務器返回內容的文本域
              JTextArea outputArea;

              
          // 客戶端socket對象
              SimpleClient client;

              
          // 在構造函數中完成圖形界面的初始化
              public ClientFrame() {
                  JLabel label1 
          = new JLabel("輸入: ");
                  inputField 
          = new JTextField(20);
                  JPanel panel1 
          = new JPanel();
                  panel1.add(label1);
                  panel1.add(inputField);

                  JLabel label2 
          = new JLabel("服務器返回: ");
                  outputArea 
          = new JTextArea(620); 
                  JScrollPane crollPane 
          = new JScrollPane(outputArea);
                  JPanel panel2 
          = new JPanel();
                  panel2.setLayout(
          new BorderLayout());
                  panel2.add(label2, BorderLayout.NORTH);
                  panel2.add(crollPane, BorderLayout.CENTER);

                  sendButton 
          = new JButton("發 送");
                  sendButton.addActionListener(
          this);
                  
                  JPanel panel 
          = new JPanel(); 
                  panel.setLayout(
          new BorderLayout()); 
                  panel.add(panel1, BorderLayout.NORTH);
                  panel.add(sendButton, BorderLayout.CENTER);
                  panel.add(panel2, BorderLayout.PAGE_END);

                  setTitle(
          "Socket 客戶端");
                  
          this.getContentPane().add(panel);
                  
          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              }


              
          public void actionPerformed(ActionEvent ae) {
                  
          // 判斷事件源控件是否是"發送"按鈕
                  if (ae.getSource() == sendButton) {
                      
          try {
                          
          // 發送文本框中的文本
                          client.sendRequest(inputField.getText()); 
                      }
           catch (Exception ex) {
                          ex.printStackTrace();
                      }

                      
          // 接收服務器回應并寫入文本域
                      outputArea.append(client.getResponse() + "\n"); 
                  }

              }


              
          public static void main(String[] args) {
                  ClientFrame frame 
          = new ClientFrame();
                  frame.pack();
                  
          // 連接服務器
                  frame.client = new SimpleClient("127.0.0.1"8888); 
                  frame.setVisible(
          true);

              }


          }







                                                                                                                 --    學海無涯
                  

          主站蜘蛛池模板: 离岛区| 额尔古纳市| 乐亭县| 甘谷县| 盐津县| 方城县| 偏关县| 华亭县| 柳州市| 湟源县| 襄垣县| 嵊泗县| 定结县| 隆林| 汉沽区| 上虞市| 民权县| 泗阳县| 彭泽县| 阳谷县| 松原市| 左云县| 周宁县| 巴彦淖尔市| 平顶山市| 吉首市| 延庆县| 宁陕县| 兴文县| 田东县| 宁国市| 庆安县| 视频| 永登县| 九台市| 东兴市| 宜良县| 桐庐县| 顺昌县| 高要市| 盐源县|