package com.cisdi.data.emserver.gateway.impl;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

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

import com.cisdi.data.common.exception.BusinessException;

public class SocketClient {
	
	private static Logger logger = LoggerFactory.getLogger(SocketClient.class);
	
	//连接服务器的IP 
	public String ip = null;
	//连接服务器的端口 
	public Integer port = null;
	//套节字对象 
	private Socket socket = null;
	//超时时间，以毫秒为单位 
	private Integer timeout = 2000;
	
	public SocketClient(String ip, Integer port) {
		this.ip = ip;
		this.port = port;
	}
	
	/**
	* 打开连接
	*/ 
	public void open(){
	    try {
			socket = new Socket();
			socket.connect(new InetSocketAddress(ip, port), timeout);//设置连接请求超时时间
		    socket.setKeepAlive(true);//开启保持活动状态的套接字 
		    socket.setSoTimeout(timeout);//设置超时时间 
		} catch (UnknownHostException e) {
			logger.error(e.getMessage(),e);
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
		} 
	}
	
	/**
	* 发送数据（同步返回）
	* @param data
	* @return
	*/ 
	public String send(byte[] data) {
		
		String resultString = null;
		
		DataOutputStream out = null;
		try {
			out = new DataOutputStream(socket.getOutputStream());
			
			out.write(data);
			out.flush();
			
		} catch (Exception e) {
			throw new BusinessException(e.getMessage(), e);
		}  finally {
			if (out != null){
				try {
					out.close();
				} catch (IOException e) {
					logger.error("DataOutputStream out 关闭异常：", e);
				}
			}
		}
		
		return resultString;
	}
	
	public void close() {
		if(socket != null) {
			try {
				socket.close();
			} catch (IOException e) {
				logger.warn(e.getLocalizedMessage(), e);
			}
		}
	}


	public static void main(String[] args) throws UnsupportedEncodingException
	{
		String testmsg=(char)0x02+",T1234,S0123456789ABCDEFGHIJ,C12.345678 ,S12.345678 ,W 0.987654 ,C  36,S  45,M012,H12:00,D01M12Y10,"+(char)0x0a+(char)0x0b+",A001196302303,N   "+(char)0x0a+(char)0x0b+(char)0x03;

		SocketClient socketClient=new SocketClient("10.76.48.66",5002);
		socketClient.open();
		socketClient.send(testmsg.getBytes());
		socketClient.close();
	}
}
