温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java中怎么实现 Socket通信

发布时间:2021-07-20 14:01:51 阅读:178 作者:Leah 栏目:编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

本篇文章为大家展示了Java中怎么实现 Socket通信,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

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(UnioncomDeliver.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通信,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×