论坛首页 Java企业应用论坛

一个c(C++)程序员来写Java时,且看代码风格啥效果~~

浏览 15845 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2014-11-28  
happysoul 写道
truekbcl 写道
我只觉得楼主很2。

楼主都说了 是粘贴别人的代码 拜托回复消息稍微看一眼文字 乱喷
这写法是没有问题的 只是写java的人看着会觉得奇葩而已
java比c的写法 就是内存的自动回收部分会看着让写C的人一时不能习惯
如果你写js的话也会遇到内存不释放的情况 必须手动将使用的变量置为null 尤其体现在低版本的IE上面,仅仅是刷新页面都会让内存暴增

就举个列子来看看c语言程序员在写java时候的守旧的思想吧··
----------------------------------
请仔细想想这句话。
0 请登录后投票
   发表时间:2014-11-28  
好多年没看到java程序员 吐槽别人的代码风格了.
java程序员一般不都是被吐槽写的罗嗦老土么....
0 请登录后投票
   发表时间:2014-11-29   最后修改:2014-11-29
u013830484 写道
最近看公司的源码,早就知道初期的源码是一帮c语言的人勉强写的了,过不其然,就举个列子来看看c语言程序员在写java时候的守旧的思想吧··
                ArrayList<TaskInfo> list = new ArrayList<TaskInfo>();
TaskInfo personal_task_info = new TaskInfo();
personal_task_info.mstrID = CONST_SEL_WELFARE;
list.add(personal_task_info);
personal_task_info = null;
if(!UserInfoMgr.isTodaySignIn())
{
personal_task_info = new TaskInfo();
personal_task_info.mstrID = CONST_PERSONAL_SIGNIN;
list.add(personal_task_info);
personal_task_info = null;
}

两次personal_task_info = null;就把我弄醉了·····


给你贴一个真正的 C/C++ 程序员的JAVA代码:


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

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

/**
* 日期对象与字符串对象相互转换类
* @Package com.net263.ccap.common.util
* @File DateUtil.java
* @date 2014-10-13 下午10:35:25
*/
public class DateUtil {

    private static final Logger log = LoggerFactory
        .getLogger(DateUtil.class);
   
    /**
     * 将字符串类型的日期转为 Date 类型
     * @param dateString 字符串类型的日期
     * @return {Date} 返回 null 表示输入参数错误或转换出错
     */
    public static Date dateOf(String dateString, String dateFormat) {
        if (dateString == null || dateString.isEmpty())
            return null;
       
        SimpleDateFormat format;
        if (dateFormat != null && !dateFormat.isEmpty())
            format = new SimpleDateFormat(dateFormat);
        else
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date;
        try {
            date = format.parse(dateString);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("invalid date format: " + dateString);
            return null;
        }
        return date;
    }
   
    /**
     * 将 Date 类型的日期转为 String 类开
     * @param date java.util.Date 类开的日期变量
     * @return {String} 转换出错则返回 空的字符串对象
     */
    public static String stringOf(Date date, String dateFormat) {
        if (date == null)
            return new String();
       
        SimpleDateFormat format;
        if (dateFormat != null && !dateFormat.isEmpty())
            format = new SimpleDateFormat(dateFormat);
        else
            format = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        String dateString;
        try {
            dateString = format.format(date);
        } catch (Exception e) {
            // TODO: handle exception
            log.error("invalid date: " + date);
            return new String();
        }
        return dateString;
    }
   
    /**
     * 将 long 类型的日期转为 Date 类开
     * @param date java.util.Date 类开的日期变量
     * @return {String} 转换出错则返回 空的字符串对象
     */
    public static Date dateOf(long dateLong, String dateFormat){
       
        SimpleDateFormat format;
        if (dateFormat != null && !dateFormat.isEmpty())
            format = new SimpleDateFormat(dateFormat);
        else
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString=format.format(dateLong*1000);
        Date date=null;
        try {
            date=format.parse(dateString);
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        return date;
    }
   
    /**
     * 将字符串格式的日期转为 1970 以来的毫秒数,如果要转成秒,则调用者需要自己
     * 将该方法的返回值除以 1000
     * @param dateString
     * @param dateFormat 日期格式:yyyy-MM-dd HH:mm:ss,当该参数为 null 时,
     *  则内部采用格式:yyyy-MM-dd HH:mm:ss
     * @return {long} 转换后的结果,返回值若为 -1 则表示出错
     */
    public static long timeOf(String dateString, String format) {
        if (format == null)
            format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        Date date;
        try {
            date = dateFormat.parse(dateString);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("invalid date: " + dateString + ", format: " + format);
            return -1;
        }
        long time = date.getTime();
        return time;
    }
   
}


import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;

import org.apache.axis.utils.ByteArrayOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.common.vo.HostVO;
import com.exception.CcapException;
import com.exception.ExceptionUtil;

/**
* 网络套接口基础通信类
* @Package com.common.socket
* @File SocketClient.java
* @author xxx@xxx.xxx
* @date 2014-9-17 下午01:41:48
*/
public class SocketClient implements Closeable {
    private static final Logger log = LoggerFactory
            .getLogger(SocketClient.class);

    private Socket socket = null;
    private HostVO host = null;

    public SocketClient(HostVO host) {
        this.host = host;
    }

    public HostVO getHost() {
        return host;
    }

    /**
     * 连接远程服务器,在进行网络读写之前必须先调用本函数连接远程服务器
     * @return 连接服务器是否成功
     */
    public boolean connect() {
        socket = new Socket();
        SocketAddress address = new InetSocketAddress(host.getIP(),
                host.getPort());

        try {
            socket.setSoTimeout(host.getSoTimeout());
            socket.setTcpNoDelay(true);
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("setSoTimeout failed, host: " + host.toString());
            socket = null;
            return false;
        }

        try {
            socket.connect(address, host.getConnectTimeout());
            return true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            log.error("connect server error, host: " + host.toString());
            e.printStackTrace();
            try {
                if (socket.isConnected())
                    socket.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            socket = null;
            return false;
        }
    }

    /**
     * 关闭网络连接,调用 connect 成功后必须调用此函数关闭连接,
     * 否则会造成 文件描述符泄露问题
     */
    @Override
    public void close() {
        try {
            if (socket != null && socket.isConnected())
                socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("close socket error");
        }

        socket = null;
    }

    public Socket getSocket() {
        return socket;
    }

    public InputStream getInputStream() throws IOException {
        return socket.getInputStream();
    }

    public OutputStream getOutPutStream() throws IOException {
        return socket.getOutputStream();
    }

    /**
     * 读一个字节数据
     * @return 返回所读字节的 ASCII 值,若返回值为 -1 则表示出错
     */
    public int readOneByte() {
        if (socket == null || !socket.isConnected()) {
            log.error("server not connected, host: " + host.toString());
            return -1;
        }
       
        InputStream in;
        try {
            in = socket.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("getInputStream error, host: " + host.toString());
            close();
            return -1;
        }

        try {
            int ch = in.read();
            return ch;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("read one byte error, host: " + host.toString());
            close();
            return -1;
        }
    }

    /**
     * 只读一次数据,所读到的数据长度不得超过限定值
     * @param maxLength 所读数据的最大长度限制,即读到的数据长度不得超过此值,
     *  该值必须 > 0
     * @return {String} 返回读到的数据,若返回 null 则表示读出错或读到 0 个字节
     */
    public String readOnce(int maxLength) {
        if (maxLength <= 0) {
            log.error("invalid maxLength: " + maxLength);
            throw new CcapException(ExceptionUtil.INVALID_PARAMS,
                    "invalid maxLength: " + maxLength);
        }
       
        if (socket == null || !socket.isConnected()) {
            log.error("server not connected, host: " + host.toString());
            return null;
        }
       
        InputStream in;
       
        try {
            in = socket.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("getInputStream error, host: " + host.toString());
            close();
            return null;
        }
       
        byte[] buf = new byte[maxLength];
        int n;
        try {
            n = in.read(buf);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("read error, host: " + host.toString());
            close();
            return null;
        }
        if (n <= 0) {
            log.error("invalid read n: " + n + "; host: " + host.toString());
            close();
            return null;
        }
        try {
            return new String(buf, 0, n, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
   
    /**
     * 读一行数据
     * @return 如果读出错则返回 null
     */
    public String getLine() {
        if (socket == null || !socket.isConnected()) {
            log.error("server not connected, host: " + host.toString());
            return null;
        }
       
        InputStream in;
        try {
            in = socket.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("getInputStream error, host: " + host.toString());
            close();
            return null;
        }

        BufferedReader reader;
        try {
            reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return null;
        }
       
        String buf;
        try {
            buf = reader.readLine();
            return buf;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("readline error, host: " + host.toString());
            close();
            return null;
        }
    }

    /**
     * 读以某个字符串为分隔符的数据
     * @param tag 分隔符字符串
     * @return 出错时返回 null;如果找到分隔符,则返回的数据中 不包含分隔串,
     *  仅返回数据部分;当读到的数据正好与分隔符相同时, 则 返回的
     *  String 对象的 length 为 0,即仅读到了分隔符
     */
    public String getByToken(String tag) {
        if (socket == null || !socket.isConnected()) {
            log.error("server not connected, host: " + host.toString());
            return null;
        }
       
        InputStream in;
        try {
            in = socket.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("get inputstream error, host: " + host.toString());
            close();
            return null;
        }

        byte[] token = tag.getBytes();
        final int tagLen = token.length;
        byte[] buf = new byte[1024];
        int nextPos = 0;

        for (;;) {
            try {
                byte ch = (byte) in.read();
                if (ch == -1) {
                    log.error("read error, tag: " + tag);
                    return null;
                }

                // 如果缓冲区空间不足,则重新分配空间,将旧数据拷贝至新缓冲区
                if (nextPos >= buf.length) {
                    byte[] bufTmp = new byte[buf.length + 128];
                    System.arraycopy(buf, 0, bufTmp, 0, buf.length);
                    buf = bufTmp;
                }

                buf[nextPos] = ch;

                // 先比较新读到字节与分隔符的最后一个字节是否相同
                if (ch != token[tagLen - 1]) {
                    nextPos++;
                    continue;
                }

                // 从后向前比较剩余的字节是否相同

                int i = tagLen - 2, currPos = nextPos - 1;

                nextPos++;

                while (currPos >= 0) {
                    if (i <= 0) {
                        if (nextPos == tagLen)
                            return new String();
                        try {
                            return new String(buf, 0, nextPos - tagLen, "UTF-8");
                        } catch (UnsupportedEncodingException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                            return null;
                        }
                    }

                    // 如果有一个字节不同,则说明在当前已读数据中未读到分隔符
                    if (token[i] != buf[currPos])
                        break;

                    i--;
                    currPos--;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                log.error("read bye error, host: " + host.toString());
                close();
                return null;
            }
        }
    }

    /**
     * 读取指定长度的数据
     * @param length 要求读到的数据长度,必须 > 0
     * @return 返回 null 表示输入参数有错或读出错,未读到要求的长度
     */
    public String getByLength(int length) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        if (saveTo(out, length) == false)
            return null;
        byte[] buf = out.toByteArray();
        try {
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("ByteArrayOutputStream close error");
            return null;
        }
        try {
            return new String(buf, 0, length, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将指定长度的数据输出至流中,该方法要求必须读到规定字节长度的数据,否则将
     * 返回 false
     * @param out 输出流句柄
     * @param length 指定输出的长度
     * @return {boolean} 返回 true 表示已经读到规定长度的数据并成功输出至输出流中,
     *  否则返回 false
     */
    public boolean saveTo(OutputStream out, int length) {
        if (length <= 0) {
            log.warn("invalid length: " + length);
            throw new CcapException(ExceptionUtil.INVALID_PARAMS,
                    "invalid length: " + length);
        }
        if (socket == null || !socket.isConnected()) {
            log.error("server not connected, host: " + host.toString());
            return false;
        }
       
        InputStream in;
        try {
            in = socket.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("getInputStream error, host: " + host.toString());
            close();
            return false;
        }
       
        byte[] buffer = new byte[8192];
       
        // 一边从输入流中读取数据,一边将数据输出至输出流中,直到达到目标数据大小
       
        while (length > 0) {
            int n = length > buffer.length ? buffer.length : length;
            try {
                n = in.read(buffer, 0, n);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                log.error("read error, host: " + host.toString());
                close();
                return false;
            }
            if (n == -1) {
                log.error("read data failed, host: " + host.toString());
                close();
                return false;
            }
           
            // 将读到的数据输出至输出流中
            try {
                out.write(buffer, 0, n);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                log.error("write data to outPutStream error");
                close();
                return false;
            }
           
            length -= n;
        }
       
        // 刷新输出流中的缓冲区数据
        try {
            out.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("flush outPutStream error");
            close();
            return false;
        }
        return true;
    }
   
    /**
     * 发送数据
     * @param buf 需要发送的数据,length 不能为 0
     * @return {boolean} 发送是否成功
     */
    public boolean send(String buf) {
        if (socket == null || !socket.isConnected()) {
            log.error("server not connected, host: " + host.toString());
            return false;
        }
       
        OutputStream out;
        try {
            out = socket.getOutputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("getOutputStream error, host: " + host.toString());
            close();
            return false;
        }
        try {
            out.write(buf.getBytes("utf-8"));
            out.flush();
            return true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("write data error, host: " + host.toString());
            close();
            return false;
        }
    }

    // ///////////////////////////////////////////////////////////////////////

    public static boolean testReadOneByte(SocketClient client) {
        String data = "+OK\r\n";
        if (client.send(data) == false) {
            System.out.println("send data error!");
            return false;
        }
        int ch = client.readOneByte();
        if (ch == -1) {
            System.out.println("read error!");
            return false;
        }

        if (ch == '+')
            System.out.println("OK, find '+'");
        else {
            System.out.println("error, not find '+'");
            return false;
        }

        data = client.getByToken("\r\n");
        if (data == null) {
            System.out.println("getByToken error");
            return false;
        }
        System.out.println("token: " + data);
        return true;
    }

    public static boolean testGetLine(SocketClient client) {
        String data = "hello world!\r\n";
        if (client.send(data) == false) {
            System.out.println("send data failed!");
            return false;
        }
        data = client.getLine();
        if (data == null) {
            System.out.println("getLine failed!");
            return false;
        }
        System.out.println(data);
        return true;
    }

    public static boolean testGetToken(SocketClient client) {
        if (client.send("hello|name=value|\r\n") == false) {
            System.out.println("write filed!");
            return false;
        }
        String data = client.getByToken("|");
        if (data == null) {
            System.out.println("getByToken failed!");
            return false;
        }
        System.out.println("first token: " + data);

        data = client.getByToken("|");
        if (data == null) {
            System.out.println("getByToken failed!");
            return false;
        }
        System.out.println("second token: " + data);

        data = client.getByToken("\r\n");
        if (data == null) {
            System.out.println("getByToken failed!");
            return false;
        }
        System.out.println("third getByToken(len:" + data.length() + "): "
                + data);
        return true;
    }

    public static void main(String[] args) {
        final String ip = "192.168.188.173";
        int port = 8888;
        int connectTimeout = 1000;
        int soTimeout = 5000;
        HostVO host = new HostVO(ip, port);
        host.setConnectTimeout(connectTimeout).setSoTimeout(soTimeout);

        System.out.println("begin connect " + host.toString());
        SocketClient client = new SocketClient(host);
        if (client.connect() == false) {
            System.out.println("connect " + host.toString() + " error");
            return;
        }
        System.out.println("connect " + host.toString() + " ok");

        if (testReadOneByte(client) == false) {
            client.close();
            return;
        }
        if (testGetLine(client) == false) {
            client.close();
            return;
        }
        if (testGetToken(client) == false) {
            client.close();
            return;
        }
        try {
            client.getByLength(-1);           
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("get length error");
        }
       
        client.close();

        byte[] buf = new byte[256];
        buf[0] = '0';
        buf[1] = '1';
        buf[2] = '2';
        String tmp = new String(buf, 0, 3);
        System.out.println("buf: " + buf.toString() + "; byte len: "
                + buf.length + "; toString len: " + buf.toString().length());
        System.out.println("tmp: " + tmp + "; len: " + tmp.length());
        tmp = new String();
        System.out.println("tmp length: " + tmp.length());
    }
}
0 请登录后投票
   发表时间:2014-11-30  
icefishc 写道
好多年没看到java程序员 吐槽别人的代码风格了.
java程序员一般不都是被吐槽写的罗嗦老土么....


哈哈,主要是java语法糖少。不像很多现代语言有大量符号语法。
0 请登录后投票
   发表时间:2014-12-10  
icefishc 写道
好多年没看到java程序员 吐槽别人的代码风格了.
java程序员一般不都是被吐槽写的罗嗦老土么....

不是啊,我觉得java的面向对象思想用好后效率极其高,只不过要是按照c的方法来写的话自然是啰嗦了。如果说java有不够好和啰嗦的地方的话,我认为应该是泛型做的不太好······
0 请登录后投票
   发表时间:2014-12-10  
zsxxsz 写道
u013830484 写道
最近看公司的源码,早就知道初期的源码是一帮c语言的人勉强写的了,过不其然,就举个列子来看看c语言程序员在写java时候的守旧的思想吧··
                ArrayList<TaskInfo> list = new ArrayList<TaskInfo>();
TaskInfo personal_task_info = new TaskInfo();
personal_task_info.mstrID = CONST_SEL_WELFARE;
list.add(personal_task_info);
personal_task_info = null;
if(!UserInfoMgr.isTodaySignIn())
{
personal_task_info = new TaskInfo();
personal_task_info.mstrID = CONST_PERSONAL_SIGNIN;
list.add(personal_task_info);
personal_task_info = null;
}

两次personal_task_info = null;就把我弄醉了·····


给你贴一个真正的 C/C++ 程序员的JAVA代码:


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

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

/**
* 日期对象与字符串对象相互转换类
* @Package com.net263.ccap.common.util
* @File DateUtil.java
* @date 2014-10-13 下午10:35:25
*/
public class DateUtil {

    private static final Logger log = LoggerFactory
        .getLogger(DateUtil.class);
   
    /**
     * 将字符串类型的日期转为 Date 类型
     * @param dateString 字符串类型的日期
     * @return {Date} 返回 null 表示输入参数错误或转换出错
     */
    public static Date dateOf(String dateString, String dateFormat) {
        if (dateString == null || dateString.isEmpty())
            return null;
       
        SimpleDateFormat format;
        if (dateFormat != null && !dateFormat.isEmpty())
            format = new SimpleDateFormat(dateFormat);
        else
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date;
        try {
            date = format.parse(dateString);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("invalid date format: " + dateString);
            return null;
        }
        return date;
    }
   
    /**
     * 将 Date 类型的日期转为 String 类开
     * @param date java.util.Date 类开的日期变量
     * @return {String} 转换出错则返回 空的字符串对象
     */
    public static String stringOf(Date date, String dateFormat) {
        if (date == null)
            return new String();
       
        SimpleDateFormat format;
        if (dateFormat != null && !dateFormat.isEmpty())
            format = new SimpleDateFormat(dateFormat);
        else
            format = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        String dateString;
        try {
            dateString = format.format(date);
        } catch (Exception e) {
            // TODO: handle exception
            log.error("invalid date: " + date);
            return new String();
        }
        return dateString;
    }
   
    /**
     * 将 long 类型的日期转为 Date 类开
     * @param date java.util.Date 类开的日期变量
     * @return {String} 转换出错则返回 空的字符串对象
     */
    public static Date dateOf(long dateLong, String dateFormat){
       
        SimpleDateFormat format;
        if (dateFormat != null && !dateFormat.isEmpty())
            format = new SimpleDateFormat(dateFormat);
        else
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString=format.format(dateLong*1000);
        Date date=null;
        try {
            date=format.parse(dateString);
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        return date;
    }
   
    /**
     * 将字符串格式的日期转为 1970 以来的毫秒数,如果要转成秒,则调用者需要自己
     * 将该方法的返回值除以 1000
     * @param dateString
     * @param dateFormat 日期格式:yyyy-MM-dd HH:mm:ss,当该参数为 null 时,
     *  则内部采用格式:yyyy-MM-dd HH:mm:ss
     * @return {long} 转换后的结果,返回值若为 -1 则表示出错
     */
    public static long timeOf(String dateString, String format) {
        if (format == null)
            format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        Date date;
        try {
            date = dateFormat.parse(dateString);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("invalid date: " + dateString + ", format: " + format);
            return -1;
        }
        long time = date.getTime();
        return time;
    }
   
}


import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;

import org.apache.axis.utils.ByteArrayOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.common.vo.HostVO;
import com.exception.CcapException;
import com.exception.ExceptionUtil;

/**
* 网络套接口基础通信类
* @Package com.common.socket
* @File SocketClient.java
* @author xxx@xxx.xxx
* @date 2014-9-17 下午01:41:48
*/
public class SocketClient implements Closeable {
    private static final Logger log = LoggerFactory
            .getLogger(SocketClient.class);

    private Socket socket = null;
    private HostVO host = null;

    public SocketClient(HostVO host) {
        this.host = host;
    }

    public HostVO getHost() {
        return host;
    }

    /**
     * 连接远程服务器,在进行网络读写之前必须先调用本函数连接远程服务器
     * @return 连接服务器是否成功
     */
    public boolean connect() {
        socket = new Socket();
        SocketAddress address = new InetSocketAddress(host.getIP(),
                host.getPort());

        try {
            socket.setSoTimeout(host.getSoTimeout());
            socket.setTcpNoDelay(true);
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("setSoTimeout failed, host: " + host.toString());
            socket = null;
            return false;
        }

        try {
            socket.connect(address, host.getConnectTimeout());
            return true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            log.error("connect server error, host: " + host.toString());
            e.printStackTrace();
            try {
                if (socket.isConnected())
                    socket.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            socket = null;
            return false;
        }
    }

    /**
     * 关闭网络连接,调用 connect 成功后必须调用此函数关闭连接,
     * 否则会造成 文件描述符泄露问题
     */
    @Override
    public void close() {
        try {
            if (socket != null && socket.isConnected())
                socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("close socket error");
        }

        socket = null;
    }

    public Socket getSocket() {
        return socket;
    }

    public InputStream getInputStream() throws IOException {
        return socket.getInputStream();
    }

    public OutputStream getOutPutStream() throws IOException {
        return socket.getOutputStream();
    }

    /**
     * 读一个字节数据
     * @return 返回所读字节的 ASCII 值,若返回值为 -1 则表示出错
     */
    public int readOneByte() {
        if (socket == null || !socket.isConnected()) {
            log.error("server not connected, host: " + host.toString());
            return -1;
        }
       
        InputStream in;
        try {
            in = socket.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("getInputStream error, host: " + host.toString());
            close();
            return -1;
        }

        try {
            int ch = in.read();
            return ch;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("read one byte error, host: " + host.toString());
            close();
            return -1;
        }
    }

    /**
     * 只读一次数据,所读到的数据长度不得超过限定值
     * @param maxLength 所读数据的最大长度限制,即读到的数据长度不得超过此值,
     *  该值必须 > 0
     * @return {String} 返回读到的数据,若返回 null 则表示读出错或读到 0 个字节
     */
    public String readOnce(int maxLength) {
        if (maxLength <= 0) {
            log.error("invalid maxLength: " + maxLength);
            throw new CcapException(ExceptionUtil.INVALID_PARAMS,
                    "invalid maxLength: " + maxLength);
        }
       
        if (socket == null || !socket.isConnected()) {
            log.error("server not connected, host: " + host.toString());
            return null;
        }
       
        InputStream in;
       
        try {
            in = socket.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("getInputStream error, host: " + host.toString());
            close();
            return null;
        }
       
        byte[] buf = new byte[maxLength];
        int n;
        try {
            n = in.read(buf);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("read error, host: " + host.toString());
            close();
            return null;
        }
        if (n <= 0) {
            log.error("invalid read n: " + n + "; host: " + host.toString());
            close();
            return null;
        }
        try {
            return new String(buf, 0, n, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
   
    /**
     * 读一行数据
     * @return 如果读出错则返回 null
     */
    public String getLine() {
        if (socket == null || !socket.isConnected()) {
            log.error("server not connected, host: " + host.toString());
            return null;
        }
       
        InputStream in;
        try {
            in = socket.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("getInputStream error, host: " + host.toString());
            close();
            return null;
        }

        BufferedReader reader;
        try {
            reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return null;
        }
       
        String buf;
        try {
            buf = reader.readLine();
            return buf;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("readline error, host: " + host.toString());
            close();
            return null;
        }
    }

    /**
     * 读以某个字符串为分隔符的数据
     * @param tag 分隔符字符串
     * @return 出错时返回 null;如果找到分隔符,则返回的数据中 不包含分隔串,
     *  仅返回数据部分;当读到的数据正好与分隔符相同时, 则 返回的
     *  String 对象的 length 为 0,即仅读到了分隔符
     */
    public String getByToken(String tag) {
        if (socket == null || !socket.isConnected()) {
            log.error("server not connected, host: " + host.toString());
            return null;
        }
       
        InputStream in;
        try {
            in = socket.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("get inputstream error, host: " + host.toString());
            close();
            return null;
        }

        byte[] token = tag.getBytes();
        final int tagLen = token.length;
        byte[] buf = new byte[1024];
        int nextPos = 0;

        for (;;) {
            try {
                byte ch = (byte) in.read();
                if (ch == -1) {
                    log.error("read error, tag: " + tag);
                    return null;
                }

                // 如果缓冲区空间不足,则重新分配空间,将旧数据拷贝至新缓冲区
                if (nextPos >= buf.length) {
                    byte[] bufTmp = new byte[buf.length + 128];
                    System.arraycopy(buf, 0, bufTmp, 0, buf.length);
                    buf = bufTmp;
                }

                buf[nextPos] = ch;

                // 先比较新读到字节与分隔符的最后一个字节是否相同
                if (ch != token[tagLen - 1]) {
                    nextPos++;
                    continue;
                }

                // 从后向前比较剩余的字节是否相同

                int i = tagLen - 2, currPos = nextPos - 1;

                nextPos++;

                while (currPos >= 0) {
                    if (i <= 0) {
                        if (nextPos == tagLen)
                            return new String();
                        try {
                            return new String(buf, 0, nextPos - tagLen, "UTF-8");
                        } catch (UnsupportedEncodingException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                            return null;
                        }
                    }

                    // 如果有一个字节不同,则说明在当前已读数据中未读到分隔符
                    if (token[i] != buf[currPos])
                        break;

                    i--;
                    currPos--;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                log.error("read bye error, host: " + host.toString());
                close();
                return null;
            }
        }
    }

    /**
     * 读取指定长度的数据
     * @param length 要求读到的数据长度,必须 > 0
     * @return 返回 null 表示输入参数有错或读出错,未读到要求的长度
     */
    public String getByLength(int length) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        if (saveTo(out, length) == false)
            return null;
        byte[] buf = out.toByteArray();
        try {
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("ByteArrayOutputStream close error");
            return null;
        }
        try {
            return new String(buf, 0, length, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将指定长度的数据输出至流中,该方法要求必须读到规定字节长度的数据,否则将
     * 返回 false
     * @param out 输出流句柄
     * @param length 指定输出的长度
     * @return {boolean} 返回 true 表示已经读到规定长度的数据并成功输出至输出流中,
     *  否则返回 false
     */
    public boolean saveTo(OutputStream out, int length) {
        if (length <= 0) {
            log.warn("invalid length: " + length);
            throw new CcapException(ExceptionUtil.INVALID_PARAMS,
                    "invalid length: " + length);
        }
        if (socket == null || !socket.isConnected()) {
            log.error("server not connected, host: " + host.toString());
            return false;
        }
       
        InputStream in;
        try {
            in = socket.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("getInputStream error, host: " + host.toString());
            close();
            return false;
        }
       
        byte[] buffer = new byte[8192];
       
        // 一边从输入流中读取数据,一边将数据输出至输出流中,直到达到目标数据大小
       
        while (length > 0) {
            int n = length > buffer.length ? buffer.length : length;
            try {
                n = in.read(buffer, 0, n);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                log.error("read error, host: " + host.toString());
                close();
                return false;
            }
            if (n == -1) {
                log.error("read data failed, host: " + host.toString());
                close();
                return false;
            }
           
            // 将读到的数据输出至输出流中
            try {
                out.write(buffer, 0, n);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                log.error("write data to outPutStream error");
                close();
                return false;
            }
           
            length -= n;
        }
       
        // 刷新输出流中的缓冲区数据
        try {
            out.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("flush outPutStream error");
            close();
            return false;
        }
        return true;
    }
   
    /**
     * 发送数据
     * @param buf 需要发送的数据,length 不能为 0
     * @return {boolean} 发送是否成功
     */
    public boolean send(String buf) {
        if (socket == null || !socket.isConnected()) {
            log.error("server not connected, host: " + host.toString());
            return false;
        }
       
        OutputStream out;
        try {
            out = socket.getOutputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("getOutputStream error, host: " + host.toString());
            close();
            return false;
        }
        try {
            out.write(buf.getBytes("utf-8"));
            out.flush();
            return true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("write data error, host: " + host.toString());
            close();
            return false;
        }
    }

    // ///////////////////////////////////////////////////////////////////////

    public static boolean testReadOneByte(SocketClient client) {
        String data = "+OK\r\n";
        if (client.send(data) == false) {
            System.out.println("send data error!");
            return false;
        }
        int ch = client.readOneByte();
        if (ch == -1) {
            System.out.println("read error!");
            return false;
        }

        if (ch == '+')
            System.out.println("OK, find '+'");
        else {
            System.out.println("error, not find '+'");
            return false;
        }

        data = client.getByToken("\r\n");
        if (data == null) {
            System.out.println("getByToken error");
            return false;
        }
        System.out.println("token: " + data);
        return true;
    }

    public static boolean testGetLine(SocketClient client) {
        String data = "hello world!\r\n";
        if (client.send(data) == false) {
            System.out.println("send data failed!");
            return false;
        }
        data = client.getLine();
        if (data == null) {
            System.out.println("getLine failed!");
            return false;
        }
        System.out.println(data);
        return true;
    }

    public static boolean testGetToken(SocketClient client) {
        if (client.send("hello|name=value|\r\n") == false) {
            System.out.println("write filed!");
            return false;
        }
        String data = client.getByToken("|");
        if (data == null) {
            System.out.println("getByToken failed!");
            return false;
        }
        System.out.println("first token: " + data);

        data = client.getByToken("|");
        if (data == null) {
            System.out.println("getByToken failed!");
            return false;
        }
        System.out.println("second token: " + data);

        data = client.getByToken("\r\n");
        if (data == null) {
            System.out.println("getByToken failed!");
            return false;
        }
        System.out.println("third getByToken(len:" + data.length() + "): "
                + data);
        return true;
    }

    public static void main(String[] args) {
        final String ip = "192.168.188.173";
        int port = 8888;
        int connectTimeout = 1000;
        int soTimeout = 5000;
        HostVO host = new HostVO(ip, port);
        host.setConnectTimeout(connectTimeout).setSoTimeout(soTimeout);

        System.out.println("begin connect " + host.toString());
        SocketClient client = new SocketClient(host);
        if (client.connect() == false) {
            System.out.println("connect " + host.toString() + " error");
            return;
        }
        System.out.println("connect " + host.toString() + " ok");

        if (testReadOneByte(client) == false) {
            client.close();
            return;
        }
        if (testGetLine(client) == false) {
            client.close();
            return;
        }
        if (testGetToken(client) == false) {
            client.close();
            return;
        }
        try {
            client.getByLength(-1);           
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("get length error");
        }
       
        client.close();

        byte[] buf = new byte[256];
        buf[0] = '0';
        buf[1] = '1';
        buf[2] = '2';
        String tmp = new String(buf, 0, 3);
        System.out.println("buf: " + buf.toString() + "; byte len: "
                + buf.length + "; toString len: " + buf.toString().length());
        System.out.println("tmp: " + tmp + "; len: " + tmp.length());
        tmp = new String();
        System.out.println("tmp length: " + tmp.length());
    }
}


这·····
0 请登录后投票
   发表时间:2014-12-24  
多态的作用,list空了
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics