关于java socket的一些总结:

Java Socket通信有很多的时候需要我们不断的学习。方面效率虽然不及C与C++但它以灵活语言优势,为大家广为使用。 本文就对在使用java做通信方面程序时候应改注意问题做以说明。


1.长连接、短链接只是针对客户端而言,服务器无所谓长、短;

2.无论同步或者异步通信,发送之后务必要又响应回复,确认收到,负责进行一定范围内重发,例如重发三次;

3.长连接服务器与客户端之间务必需要心跳探测,由客户端主动发起;

4.短连接服务器通用代码:

package com.biesan.sms.gate.unioncom.communication;  
    import com.biesan.commons.Constants;  
    import com.biesan.commons.util.CodeUtil;  
    import com.biesan.sms.gate.unioncom.data.*;  
    import com.biesan.sms.gate.unioncom.util.GateInfo;  
    import java.net.*;  
    import java.io.*;  
    import java.util.*;  
    import org.apache.log4j.*;  
    import spApi.*;  
    public class UnioncomDeliver extends Thread {  
    // stop flag  
    private boolean unInterrupt = true;  
    private boolean unErr = true;  
    //private boolean closeSocketFlag = false;  
    // server socket  
    private ServerSocket serverSo = null;  
    // current socket  
    private Socket so = null 
    private OutputStream output = null;  
    private InputStream input = null;  
    // gate command  
    private SGIP_Command tmpCmd = null;  
    private SGIP_Command cmd = null;  
    private Bind bind = null;  
    private BindResp bindResp = null;  
    //private Unbind unBind = null;  
    private UnbindResp unBindResp = null;  
    private boolean unAcceptErrorFlag = true;  
    Logger unioncomLog = Logger.getLogger(Unioncom
    Deliver.class.getName());  
    public UnioncomDeliver() {  
    }  
    public void run() {  
    unioncomLog.info("Start...");  
    while (unInterrupt) {  
    this.initServer();  
    this.startServices();  
    while (this.unAcceptErrorFlag) {  
    try {  
    //接受连接请求  
    unioncomLog.info("before accept connection!....... 
    FreeMemroy :" + Runtime.getRuntime().freeMemory());  
    this.acceptConnection();  
    unioncomLog.info("after accept connection!....... 
    FreeMemroy :" + Runtime.getRuntime().freeMemory());  
    while (unErr) {  
    cmd = new Command();  
    unioncomLog.info("before read command from stream
    ........... FreeMemroy: " + Runtime.getRuntime().
    freeMemory());  
    tmpCmd = cmd.read(input);  
    unioncomLog.info("after read command from stream " + 
    getCommandString(cmd.getCommandID()) + " FreeMemroy: " + 
    Runtime.getRuntime().freeMemory());  
    if (tmpCmd == null) {  
    unErr = false;  
    break;  
    }  
    switch (cmd.getCommandID()) {  
    // biad ready communication  
    case SGIP_Command.ID_SGIP_BIND: {  
    this.dealBind();  
    break;  
    }// exit bind  
    case SGIP_Command.ID_SGIP_UNBIND: {  
    this.dealUnBind();  
    unioncomLog.info("after unbind connection!....... 
    FreeMemroy :" + Runtime.getRuntime().freeMemory());  
    break;  
    }// deliver  
    ....  
    default : //错误的命令字  
    break;  
    }// switch  
    }// while(unErr)  
    } catch (Exception e) {  
    unioncomLog.error("Unioncom Recv Service Error"  
    + e.getMessage());   
    } finally {  
    if (this.so != null) {  
    this.closeSocket();  
    }  
    this.unErr = true;  
    }  
    }// while (this.unAcceptErrorFlag)  
    try {  
    this.closeServerSocket();  
    sleep(200);// sleep  
    } catch (InterruptedException ie) {  
    }  
    }// while(unInterrupt)  
    }  
    private String getCommandString(int cmd){  
    switch (cmd) {  
    // biad ready communication  
    case SGIP_Command.ID_SGIP_BIND: {  
    return " BIND COMMAND ";   
    }// exit bind  
    case SGIP_Command.ID_SGIP_UNBIND: {  
    return " UNBIND COMMAND ";   
    }// deliver  
    case ...  
    default:  
    return " UNKNOWN COMMAND";   
    }  
    }  
    private void dealBind() {  
    try {  
    bind = new Bind(tmpCmd);  
    if (bind.readbody() != 0) {  
    unioncomLog.warn("Read Bind error");  
    this.unErr = false;  
    }  
    bindResp = new BindResp(tmpCmd.getMsgHead());  
    bindResp.SetResult(0);  
    bindResp.write(output);  
    unioncomLog.debug("Bind success!");  
    } catch (Exception e) {  
    unioncomLog.error("Dela Union Recv Bind Error!" + 
    e.getMessage());  
    this.unErr = false;  
    }  
    }  
    private void dealUnBind() {  
    try {  
    //unBind = (Unbind) tmpCmd;  
    unBindResp = new UnbindResp(tmpCmd.getMsgHead());  
    unBindResp.write(output);  
    unioncomLog.debug("UnBind success!");  
    } catch (Exception e) {  
    unioncomLog.warn("Unbind error!" + e.getMessage());  
    }  
    this.unErr = false;  
    }  
    private void startServices() {  
    boolean unStartServices = true;  
    while (unStartServices) {  
    try {  
    serverSo = new ServerSocket(ugInfo.getLocalServerPort(), 5,  
    InetAddress.getByName(ugInfo.getLocalIpAdd()));  
    //serverSo.setSoTimeout(60000);  
    unStartServices = false;   
    unioncomLog.info("Create union recv socket Ok!");  
    } catch (IOException e) {  
    unioncomLog.warn("Create union recv socket error!"  
    + e.getMessage());  
    unStartServices = true;  
    UnioncomSubmit.thrSlp(3000);  
    }  
    }  
    }  
    private void acceptConnection() {  
    // Accept 失败  
    try {   
    so = serverSo.accept();  
    so.setSoTimeout(10000);  
    } catch (Exception e) {  
    unioncomLog.warn("Accept Error!" + e.getMessage());  
    this.closeServerSocket();  
    this.unAcceptErrorFlag = false;  
    this.unErr=false;  
    }  
    // Accept成功  
    try {  
    input = so.getInputStream();  
    output = so.getOutputStream();  
    } catch (IOException e) {  
    unioncomLog.warn("Get I/O stream Error!" + e.getMessage());  
    this.closeService();  
    this.unAcceptErrorFlag = false;  
    this.unErr=false;  
    }  
    }  
    private void closeSocket() {  
    try {  
    so.close();  
    unioncomLog.info("Socket Close Success!!!");  
    } catch (Exception e) {  
    unioncomLog.error("Socket Close Failure!!!" + e.getMessage());  
    }  
    }  
    private void closeServerSocket() {  
    try {  
    serverSo.close();  
    unioncomLog.info("ServerSocket Close Success!!!");  
    } catch (Exception e) {  
    unioncomLog  
    .error("ServerSocket Close Failure!!!" + e.getMessage());  
    }  
    }  
    private void closeService() {  
    this.closeSocket();  
    this.closeServerSocket();  
    }  
    private void initServer() {  
    this.bind = null;  
    this.bindResp = null;  
    //this.unBind = null;  
    this.unBindResp = null;  
    this.tmpCmd = null;  
    this.cmd = null;  
    this.serverSo = null;  
    this.so = null;  
    this.output = null;  
    this.input = null;  
    this.unErr = true;  
    //this.closeSocketFlag = false;  
    unioncomLog.info("Memory***==="  
    + java.lang.Runtime.getRuntime().freeMemory());  
    }  
    public synchronized void requireStop() {  
    this.unInterrupt = false;  
    unioncomLog.info("Requre interrupt!!!");  
    }  
    public String convertMsgContentCoding
    (int msgCoding, byte[] msgContent) {  
    String deliverContent = null;  
    try {  
    if (msgContent != null) {  
    if (msgCoding == 8) { // 处理ucs32编码  
    deliverContent = new String(msgContent,  
    "UnicodeBigUnmarked");  
    } else if (msgCoding == 0) { // 处理ASCII编码  
    deliverContent = new String(msgContent, "ASCII");  
    } else if (msgCoding == 4) { // 处理binary编码  
    deliverContent = new String(msgContent);  
    } else if (msgCoding == 15) { // 处理GBK编码  
    deliverContent = new String(msgContent, "GBK");  
    // 处理DELIVER数据包的短信息ID  
    } else {  
    unioncomLog.error("编码格式错误!");  
    return "";  
    }  
    } else  
    return "";  
    return deliverContent;  
    } catch (UnsupportedEncodingException ex) {  
    unioncomLog.error("deal content error!" +
     ex.getMessage());  
    return "";  
    }  
    }  
    }

以上就是对Java Socket通信的详细介绍。

如果您愿意花几块钱请我喝杯茶的话,可以用手机扫描下方的二维码,通过 支付宝 捐赠。我会努力写出更好的文章。 
(捐赠不显示捐赠者的个人信息,如需要,请注明您的联系方式) 
Thank you for your kindly donation!!

  1.  
 

自然语言交流系统 phxnet团队 创新实训 个人博客 (十三)的更多相关文章

  1. 自然语言交流系统 phxnet团队 创新实训 个人博客 (五)

    有关我们这个项目:智能自然语言交流系统,所借鉴的技术有: 第一:我们使用了科大讯飞的在线语音转换,涉及的有文本传给云端服务器的文字转换成语音和本地的语音上传给服务器转换成文字. 涉及的相关的代码有: ...

  2. 自然语言交流系统 phxnet团队 创新实训 项目博客 (四)

    刚开始做时,一点头绪都没有,整天的上网找资料,各种谷歌百度,各种博客论坛,搜索的关键词也无非是智能自然语言交流.智能机器人.中文问答系统等等等等.而我们的思路也是些零散的,例如我们知道会用到分词,会用 ...

  3. 自然语言交流系统 phxnet团队 创新实训 项目博客 (二)

    基本要求 打开软件,即可进入2D文本交流界面, 软件此时已经连接到服务器,点击文本输入框输入你想说的话,点击发送按钮即可进行交流,点击CHAT和STUDY分别切换到聊天模式或是学习模式,聊天模式是机器 ...

  4. 自然语言交流系统 phxnet团队 创新实训 个人博客 (十一)

    名思义是 给游戏场景 添加一个 天空背景 让游戏更加精美,更具有魅力 添加天空盒 有两种方式  1 : 在当前相机上添加skybox   2 : 在当前场景上添加skybox 上面的两种方式的结果是一 ...

  5. 自然语言交流系统 phxnet团队 创新实训 个人博客 (九)

    情感倾向可认为是主体对某一客体主观存在的内心喜恶,内在评价的一种倾向.它由两个方面来衡量:一个情感倾向方向,一个是情感倾向度. 情感倾向方向也称为情感极性.在微博中,可以理解为用户对某客体表达自身观点 ...

  6. 自然语言交流系统 phxnet团队 创新实训 项目博客 (十四)

    项目技术借鉴报告: 一.服务器端(Server) 1.分词 分词使用的是庖丁分词.使用盘古分词词库和词素作为辅助.其中包括下载Jar包并且使用. 2.人工神经网络 以网上已有的初级网络为蓝图,结合机器 ...

  7. 自然语言交流系统 phxnet团队 创新实训 项目博客 (十三)

    对我们项目中的关键技术实现进行总结: 一.3DMax关键技术实现 1.一下的关于3DMax中对于人物的设计和操作均需要在对3DMax基础知识熟练掌握的情况下进行的. 2. 骨骼架设:首先对导入到3DM ...

  8. 自然语言交流系统 phxnet团队 创新实训 项目博客 (十二)

    关于情感词典的学习总结: 情感倾向可认为是主体对某一客体主观存在的内心喜恶,内在评价的一种倾向.它由两个方面来衡量:一个情感倾向方向,一个是情感倾向度. 情感倾向方向也称为情感极性.在微博中,可以理解 ...

  9. 自然语言交流系统 phxnet团队 创新实训 项目博客 (五)

    3DMax方面所涉及的专业知识:                       (1)一下的关于3DMax中对于人物的设计和操作均需要在对3DMax基础知识熟练掌握的情况下进行的. (2)骨骼架设:首先 ...

  10. 自然语言交流系统 phxnet团队 创新实训 个人博客 (四)

    关于项目中个使用到的自然语言语音转文字&文字转语言的个人总结: VOICE_NAME, "xiaoyan");speechSynthesizer.setParameter( ...

随机推荐

  1. Objective的头文件@interface属性

    源码:http://files.cnblogs.com/ios8/TestPropertyDemo.zip 1 前言 最近有个疑惑 @interface中的属性和@property声明的属性有什么区别 ...

  2. android 中毛玻璃效果的实现

    最近在做一款叫叽叽的App(男银懂的),其中有一个功能需要对图片处理实现毛玻璃的特效 进过一番预研,找到了3中实现方案,其中各有优缺点: 1.如果系统的api在16以上,可以使用系统提供的方法直接处理 ...

  3. android 自己定义视频播放器之2/1

    非常久没更新博客,相信大家年后都比較忙. 今天给大家带来了一款视频播放器,首先确认的得有几点. 1.首先得有个播放视频的view. 2.加点额外功能进去左边上下滑动调节亮度,右边上下滑动调节声量: 3 ...

  4. Webbench是有名的网站压力测试工具

    [root@666 webbench-1.5]# yum install ctags [root@666 webbench-1.5]#make && make install inst ...

  5. Adventures in deep learning

    转:https://github.com/GKalliatakis/Adventures-in-deep-learning Adventures in deep learning State-of-t ...

  6. (转)Go和HTTPS

    转自:http://studygolang.com/articles/2946 Go和HTTPS  2015-04-30   bigwhite  阅读 5688 次   4 人喜欢  3 条评论  收 ...

  7. TensorFlow学习路径【转】

    作者:黄璞链接:https://www.zhihu.com/question/41667903/answer/109611087来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明 ...

  8. 【驱动】DM9000A网卡驱动框架源码分析

    Linux网络设备结构 首先看一下Linux网络设备的结构,如下图: 网络协议接口层向网络层协议提供提供统一的数据包收发接口,不论上层协议为ARP还是IP,都通过dev_queue_xmit()函数发 ...

  9. H3C部分笔记

    进入交换机各个视图的命令如下图: 用户视图 系统视图 查看历史命令 配置历史命令缓存大小为30 配置Heade信息 Header 3种类型: incoming:登录终端用户界面时的提示信息. logi ...

  10. 设计模式之原型模式(深入理解OC中的NSCopying协议以及浅拷贝、深拷贝)

    原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象.原型模式其实就是从一个对象再创建另一个可定制的对象,而且不需知道任何创建的细节. 比如说,有一个Person类,有firstN ...