java Socket 用戶端實踐

來源:互聯網
上載者:User
 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SocketClient {
 protected final static Log log = LogFactory.getLog(SocketClient.class);
 
 private static final int RECEIVE_BUFFER_SIZE = 102400;
 
 private Socket clientSocket = null;
 
 private String host = "127.0.0.1";
 
 private int port = 6600;
 
 private BufferedInputStream in;

    private BufferedOutputStream out;
   
    @SuppressWarnings("unused")
 private String charset = "gbk";
   
    public SocketClient(String host, int port) {
     this.host = host;
     this.port = port;
    }
   
    /**
  *
  * 發送資訊
  *
  * @param bData
  * name 線程名
  */
 public void send(byte[] bData, String name) {
        try {
         log.debug("線程:" + name + "    send data..... ");
            out.write(bData);
            out.flush();
        } catch (Throwable ex) {
            throw new RuntimeException(ex);
        }
    }
 
 /**
  * 建立SOCKET串連
  * name 線程名
  * @throws Throwable
  * @throws IOException
  * @throws UnknownHostException
  * @throws IOException
  * @throws UnknownHostException
  */
 public void openSocket(String name) {
  try {
  log.debug("線程:" + name + "   主機:" + host + ";連接埠:" + port + " 建立串連");
  clientSocket = new Socket(host, port);
  in = new BufferedInputStream(clientSocket.getInputStream());
     out = new BufferedOutputStream(clientSocket.getOutputStream());
  } catch (Throwable e) {
   throw new RuntimeException("線程:" + name + "   主機:" + host + ";連接埠:" + port + "  異常。 ", e);
  }
 }
 
 /**
  *
  * 發送資訊
  *
  * @param bData
  *
  */
 public void send(byte[] bData) {
        try {
            out.write(bData);
            out.flush();
        } catch (Throwable ex) {
            throw new RuntimeException(ex);
        }
    }
 
 /**
  * 建立SOCKET串連
  * name 線程名
  */
 public void openSocket() {
  try {
   log.debug("   主機:" + host + ";連接埠:" + port + " 建立串連");
   clientSocket = new Socket(host, port);
   in = new BufferedInputStream(clientSocket.getInputStream());
         out = new BufferedOutputStream(clientSocket.getOutputStream());
  } catch (Throwable e) {
   throw new RuntimeException(e);
  }
 }
 
 /**
  * 斷開SOCKET串連
  */
 public void closeSocket() {
  if (clientSocket != null) {
   try {
    log.debug("close socket");
    clientSocket.close();
   } catch (Throwable e) {
    throw new RuntimeException(e);
   }
  }
  clientSocket = null;
    }
 
 /**
  * name 線程名稱
  *
  * 斷開SOCKET串連
  */
 public void closeSocket(String name) {
  if (clientSocket != null) {
   try {
    log.debug("線程:" + name + "close socket");
    clientSocket.close();
   } catch (Throwable e) {
    throw new RuntimeException(e);
   }
  }
  clientSocket = null;
    }
 
 /**
  * 讀取回傳資訊
  *
  * @return
  * @throws Exception
  * @throws SocketException
  */
 public byte[] receive() throws Exception, SocketException {
        byte rsp[] = new byte[RECEIVE_BUFFER_SIZE];
        int iIndex = 0;
        if ((clientSocket == null) || (in == null)) {
         log.debug("套介面無效,無法讀取資料");
         log.error("套介面無效,無法讀取資料");
            throw new SocketException("套介面無效,無法讀取資料");
        }
        int iTimeoutTimes = 600;
        int iAvailable = 0;
        while (true) {
            iAvailable = in.available();

            if (iAvailable != 0) {
                for (int i = 0; i < iAvailable; i++) {
                    int temp_data = in.read();
                    if (temp_data != -1) {
                        rsp[iIndex + 0] = (byte) (temp_data & 0x0ff);
                        iIndex++;
                        if (iIndex >= RECEIVE_BUFFER_SIZE) {
                         log.debug("緩衝區長度過小,無法繼續接收CM返回結果!");
                         log.error("緩衝區長度過小,無法繼續接收CM返回結果!");
                            throw new RuntimeException("緩衝區長度過小,無法繼續接收CM返回結果!");
                        }
                    }
                }
                break;
            }
            Thread.sleep(200);
            iTimeoutTimes--;

            if (clientSocket == null)
                break;
        }
        byte[] result = new byte[iIndex];
  for (int i = 0; i < iIndex; i++) {
   result[i] = rsp[i];
  }
  return result;
 }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.