`
默默的小熊
  • 浏览: 227503 次
社区版块
存档分类
最新评论

TSocket

阅读更多

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * Socket implementation of the TTransport interface. To be commented soon!
 *
 */
public class TSocket extends TIOStreamTransport {

  private static final Logger LOGGER = LoggerFactory.getLogger(TSocket.class.getName());

  /**
   * Wrapped Socket object
   */
  private Socket socket_ = null;

  /**
   * Remote host
   */
  private String host_  = null;

  /**
   * Remote port
   */
  private int port_ = 0;

  /**
   * Socket timeout
   */
  private int timeout_ = 0;

  /**
   * Constructor that takes an already created socket.
   *
   * @param socket Already created socket object
   * @throws TTransportException if there is an error setting up the streams
   */
  public TSocket(Socket socket) throws TTransportException {
    socket_ = socket;
    try {
      socket_.setSoLinger(false, 0);
      socket_.setTcpNoDelay(true);
    } catch (SocketException sx) {
      LOGGER.warn("Could not configure socket.", sx);
    }

    if (isOpen()) {
      try {
        inputStream_ = new BufferedInputStream(socket_.getInputStream(), 1024);
        outputStream_ = new BufferedOutputStream(socket_.getOutputStream(), 1024);
      } catch (IOException iox) {
        close();
        throw new TTransportException(TTransportException.NOT_OPEN, iox);
      }
    }
  }

  /**
   * Creates a new unconnected socket that will connect to the given host
   * on the given port.
   *
   * @param host Remote host
   * @param port Remote port
   */
  public TSocket(String host, int port) {
    this(host, port, 0);
  }

  /**
   * Creates a new unconnected socket that will connect to the given host
   * on the given port.
   *
   * @param host    Remote host
   * @param port    Remote port
   * @param timeout Socket timeout
   */
  public TSocket(String host, int port, int timeout) {
    host_ = host;
    port_ = port;
    timeout_ = timeout;
    initSocket();
  }

  /**
   * Initializes the socket object
   */
  private void initSocket() {
    socket_ = new Socket();
    try {
      socket_.setSoLinger(false, 0);
      socket_.setTcpNoDelay(true);
      socket_.setSoTimeout(timeout_);
    } catch (SocketException sx) {
      LOGGER.error("Could not configure socket.", sx);
    }
  }

  /**
   * Sets the socket timeout
   *
   * @param timeout Milliseconds timeout
   */
  public void setTimeout(int timeout) {
    timeout_ = timeout;
    try {
      socket_.setSoTimeout(timeout);
    } catch (SocketException sx) {
      LOGGER.warn("Could not set socket timeout.", sx);
    }
  }

  /**
   * Returns a reference to the underlying socket.
   */
  public Socket getSocket() {
    if (socket_ == null) {
      initSocket();
    }
    return socket_;
  }

  /**
   * Checks whether the socket is connected.
   */
  public boolean isOpen() {
    if (socket_ == null) {
      return false;
    }
    return socket_.isConnected();
  }

  /**
   * Connects the socket, creating a new socket object if necessary.
   */
  public void open() throws TTransportException {
    if (isOpen()) {
      throw new TTransportException(TTransportException.ALREADY_OPEN, "Socket already connected.");
    }

    if (host_.length() == 0) {
      throw new TTransportException(TTransportException.NOT_OPEN, "Cannot open null host.");
    }
    if (port_ <= 0) {
      throw new TTransportException(TTransportException.NOT_OPEN, "Cannot open without port.");
    }

    if (socket_ == null) {
      initSocket();
    }

    try {
      socket_.connect(new InetSocketAddress(host_, port_), timeout_);
      inputStream_ = new BufferedInputStream(socket_.getInputStream(), 1024);
      outputStream_ = new BufferedOutputStream(socket_.getOutputStream(), 1024);
    } catch (IOException iox) {
      close();
      throw new TTransportException(TTransportException.NOT_OPEN, iox);
    }
  }

  /**
   * Closes the socket.
   */
  public void close() {
    // Close the underlying streams
    super.close();

    // Close the socket
    if (socket_ != null) {
      try {
        socket_.close();
      } catch (IOException iox) {
        LOGGER.warn("Could not close socket.", iox);
      }
      socket_ = null;
    }
  }

}
 
分享到:
评论

相关推荐

    TTSocket_V1_1_4.zip_TTSocket_V1_1_4_delphi tsocket

    Tsocket component for comunication Delphi 7

    TCP Socket类

    #if defined AFX TSOCKET H ECFF7A02 DCAF 455D 97C3 0C1D465D977B INCLUDED #define AFX TSOCKET H ECFF7A02 DCAF 455D 97C3 0C1D465D977B INCLUDED #if MSC VER &gt; 1000 #pragma once #endif MSC VER &gt; ...

    thrift初步了解

    TSocket 阻塞的io TFramedTransport 非阻塞io TFileTransport 可以将一组thrift请求写到文件中 TMemoryTransport 使用内存 I/O TZlibTransport 使用zlib压缩 支持的server TSimpleServer 单线程 阻塞 ...

    国人开发强悍IOCP代码Code

    s: TSocket; begin s := Winsock2.socket(AF_INET, SOCK_STREAM, IPPROTO_IP); if (s = Winsock2.INVALID_SOCKET) then raise TException.Create(ErrWin32Error, GetLastError(), 'Winsock2.socket'); m_...

    Delphi 网络远程唤醒

    MSocket: TSocket; SockAddrIn: TSockAddrIn; RetVal, OptVal, i: Integer; MacAddr: array[0..5] of Byte; MagicData: array[0..101] of Byte; Position: Longint; begin try if Length(SAddr) &lt;&gt; 17 then ...

    qt tcpsocket 传送结构体信息

    根据霍亚飞的例程结合C++ GUI QT4修改,完成的qt socket 传送结构体的例子,client和server都有,希望大家指正。

    一个简单的PHP封装的socket的client端的类

    可以完成简单的和server端的通信,包括接收和发送数据 可以根据需要完善其来对要发送的数据进行过滤 其他功能还有: 返回所有错误信息 返回最后一次错误信息 返回获取最后一次发送的消息 等等,还可以根据需要将其...

    php使用thrift客户端访问服务器测试

    php 使用thrift客户端访问服务器测试 下载后 放到站点根目录,设置 thrift_test.php里的 $socket = new TSocket('10.200.28.43', 10001); 修改为默认服务器和端口 后 直接访问 http://localhost/thrift_test.php

    从Thrift服务框架思考服务器框架-真的很有收获

    TTransport(负则传输的模块,就是底层I/O的实现):每一种传输方式都对应一个该模块,比如TSocket负则Socket通信,负责传输的对象就是Message。 TProtocol:这个就是协议模块,因为对Message的传输需要统一,否则就...

    积分java源码-thrift-interface-definitions:节俭接口定义

    积分java源码 Thrift 接口定义 符号和协议 在这里和之后,我们将 ...区块链网络节点简称为“节点”或“信用节点”,任何外部...传输序列化,以及9090与TBinaryProtocol和TSocket传输支持它的客户。 我们完整的 API 规范

    php-thrift-mapper:将PHP数组转换为Apache Thrift结构类型

    这是什么? 节俭的结构;... class Bonk { static $ _TSPEC ; /** * @var string */ public $ message = null ; /** * @var int */ public $ type = null ; public function __construct ( $ vals = null ) { if (!...

    python hbase读取数据发送kafka的方法

    本例子实现从hbase获取数据,并发送kafka。 使用 #!/usr/bin/env python ...from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryPro

    thrift-connection-pool

    此实现创建 TSocket 的实例并将它们池化。 以下代码片段显示了如何创建 TSocketProvider 的实例 GenericObjectPoolConfig config = new GenericObjectPoolConfig (); // The followings are the minimum required...

Global site tag (gtag.js) - Google Analytics