Java中怎么实现 Socket通信

发布时间:2021-07-20 14:01:51 作者:Leah
来源:亿速云 阅读:151

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

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

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

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

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

  1. package com.biesan.sms.gate.unioncom.communication;  

  2. import com.biesan.commons.Constants;  

  3. import com.biesan.commons.util.CodeUtil;  

  4. import com.biesan.sms.gate.unioncom.data.*;  

  5. import com.biesan.sms.gate.unioncom.util.GateInfo;  

  6. import java.net.*;  

  7. import java.io.*;  

  8. import java.util.*;  

  9. import org.apache.log4j.*;  

  10. import spApi.*;  

  11. public class UnioncomDeliver extends Thread {  

  12. // stop flag  

  13. private boolean unInterrupt = true;  

  14. private boolean unErr = true;  

  15. //private boolean closeSocketFlag = false;  

  16. // server socket  

  17. private ServerSocket serverSo = null;  

  18. // current socket  

  19. private Socket so = null 

  20. private OutputStream output = null;  

  21. private InputStream input = null;  

  22. // gate command  

  23. private SGIP_Command tmpCmd = null;  

  24. private SGIP_Command cmd = null;  

  25. private Bind bind = null;  

  26. private BindResp bindResp = null;  

  27. //private Unbind unBind = null;  

  28. private UnbindResp unBindResp = null;  

  29. private boolean unAcceptErrorFlag = true;  

  30. Logger unioncomLog = Logger.getLogger(Unioncom
    Deliver.class.getName());  

  31. public UnioncomDeliver() {  

  32. }  

  33. public void run() {  

  34. unioncomLog.info("Start...");  

  35. while (unInterrupt) {  

  36. this.initServer();  

  37. this.startServices();  

  38. while (this.unAcceptErrorFlag) {  

  39. try {  

  40. //接受连接请求  

  41. unioncomLog.info("before accept connection!....... 
    FreeMemroy :" + Runtime.getRuntime().freeMemory());  

  42. this.acceptConnection();  

  43. unioncomLog.info("after accept connection!....... 
    FreeMemroy :" + Runtime.getRuntime().freeMemory());  

  44. while (unErr) {  

  45. cmd = new Command();  

  46. unioncomLog.info("before read command from stream
    ........... FreeMemroy: " + Runtime.getRuntime().
    freeMemory());  

  47. tmpCmd = cmd.read(input);  

  48. unioncomLog.info("after read command from stream " + 
    getCommandString(cmd.getCommandID()) + " FreeMemroy: " + 
    Runtime.getRuntime().freeMemory());  

  49. if (tmpCmd == null) {  

  50. unErr = false;  

  51. break;  

  52. }  

  53. switch (cmd.getCommandID()) {  

  54. // biad ready communication  

  55. case SGIP_Command.ID_SGIP_BIND: {  

  56. this.dealBind();  

  57. break;  

  58. }// exit bind  

  59. case SGIP_Command.ID_SGIP_UNBIND: {  

  60. this.dealUnBind();  

  61. unioncomLog.info("after unbind connection!....... 
    FreeMemroy :" + Runtime.getRuntime().freeMemory());  

  62. break;  

  63. }// deliver  

  64. ....  

  65. default : //错误的命令字  

  66. break;  

  67. }// switch  

  68. }// while(unErr)  

  69. } catch (Exception e) {  

  70. unioncomLog.error("Unioncom Recv Service Error"  

  71. + e.getMessage());   

  72. } finally {  

  73. if (this.so != null) {  

  74. this.closeSocket();  

  75. }  

  76. this.unErr = true;  

  77. }  

  78. }// while (this.unAcceptErrorFlag)  

  79. try {  

  80. this.closeServerSocket();  

  81. sleep(200);// sleep  

  82. } catch (InterruptedException ie) {  

  83. }  

  84. }// while(unInterrupt)  

  85. }  

  86. private String getCommandString(int cmd){  

  87. switch (cmd) {  

  88. // biad ready communication  

  89. case SGIP_Command.ID_SGIP_BIND: {  

  90. return " BIND COMMAND ";   

  91. }// exit bind  

  92. case SGIP_Command.ID_SGIP_UNBIND: {  

  93. return " UNBIND COMMAND ";   

  94. }// deliver  

  95. case ...  

  96. default:  

  97. return " UNKNOWN COMMAND";   

  98. }  

  99. }  

  100. private void dealBind() {  

  101. try {  

  102. bind = new Bind(tmpCmd);  

  103. if (bind.readbody() != 0) {  

  104. unioncomLog.warn("Read Bind error");  

  105. this.unErr = false;  

  106. }  

  107. bindResp = new BindResp(tmpCmd.getMsgHead());  

  108. bindResp.SetResult(0);  

  109. bindResp.write(output);  

  110. unioncomLog.debug("Bind success!");  

  111. } catch (Exception e) {  

  112. unioncomLog.error("Dela Union Recv Bind Error!" + 
    e.getMessage());  

  113. this.unErr = false;  

  114. }  

  115. }  

  116. private void dealUnBind() {  

  117. try {  

  118. //unBind = (Unbind) tmpCmd;  

  119. unBindResp = new UnbindResp(tmpCmd.getMsgHead());  

  120. unBindResp.write(output);  

  121. unioncomLog.debug("UnBind success!");  

  122. } catch (Exception e) {  

  123. unioncomLog.warn("Unbind error!" + e.getMessage());  

  124. }  

  125. this.unErr = false;  

  126. }  

  127. private void startServices() {  

  128. boolean unStartServices = true;  

  129. while (unStartServices) {  

  130. try {  

  131. serverSo = new ServerSocket(ugInfo.getLocalServerPort(), 5,  

  132. InetAddress.getByName(ugInfo.getLocalIpAdd()));  

  133. //serverSo.setSoTimeout(60000);  

  134. unStartServices = false;   

  135. unioncomLog.info("Create union recv socket Ok!");  

  136. } catch (IOException e) {  

  137. unioncomLog.warn("Create union recv socket error!"  

  138. + e.getMessage());  

  139. unStartServices = true;  

  140. UnioncomSubmit.thrSlp(3000);  

  141. }  

  142. }  

  143. }  

  144. private void acceptConnection() {  

  145. // Accept 失败  

  146. try {   

  147. so = serverSo.accept();  

  148. so.setSoTimeout(10000);  

  149. } catch (Exception e) {  

  150. unioncomLog.warn("Accept Error!" + e.getMessage());  

  151. this.closeServerSocket();  

  152. this.unAcceptErrorFlag = false;  

  153. this.unErr=false;  

  154. }  

  155. // Accept成功  

  156. try {  

  157. input = so.getInputStream();  

  158. output = so.getOutputStream();  

  159. } catch (IOException e) {  

  160. unioncomLog.warn("Get I/O stream Error!" + e.getMessage());  

  161. this.closeService();  

  162. this.unAcceptErrorFlag = false;  

  163. this.unErr=false;  

  164. }  

  165. }  

  166. private void closeSocket() {  

  167. try {  

  168. so.close();  

  169. unioncomLog.info("Socket Close Success!!!");  

  170. } catch (Exception e) {  

  171. unioncomLog.error("Socket Close Failure!!!" + e.getMessage());  

  172. }  

  173. }  

  174. private void closeServerSocket() {  

  175. try {  

  176. serverSo.close();  

  177. unioncomLog.info("ServerSocket Close Success!!!");  

  178. } catch (Exception e) {  

  179. unioncomLog  

  180. .error("ServerSocket Close Failure!!!" + e.getMessage());  

  181. }  

  182. }  

  183. private void closeService() {  

  184. this.closeSocket();  

  185. this.closeServerSocket();  

  186. }  

  187. private void initServer() {  

  188. this.bind = null;  

  189. this.bindResp = null;  

  190. //this.unBind = null;  

  191. this.unBindResp = null;  

  192. this.tmpCmd = null;  

  193. this.cmd = null;  

  194. this.serverSo = null;  

  195. this.so = null;  

  196. this.output = null;  

  197. this.input = null;  

  198. this.unErr = true;  

  199. //this.closeSocketFlag = false;  

  200. unioncomLog.info("Memory***==="  

  201. + java.lang.Runtime.getRuntime().freeMemory());  

  202. }  

  203. public synchronized void requireStop() {  

  204. this.unInterrupt = false;  

  205. unioncomLog.info("Requre interrupt!!!");  

  206. }  

  207. public String convertMsgContentCoding
    (int msgCoding, byte[] msgContent) {  

  208. String deliverContent = null;  

  209. try {  

  210. if (msgContent != null) {  

  211. if (msgCoding == 8) { // 处理ucs32编码  

  212. deliverContent = new String(msgContent,  

  213. "UnicodeBigUnmarked");  

  214. } else if (msgCoding == 0) { // 处理ASCII编码  

  215. deliverContent = new String(msgContent, "ASCII");  

  216. } else if (msgCoding == 4) { // 处理binary编码  

  217. deliverContent = new String(msgContent);  

  218. } else if (msgCoding == 15) { // 处理GBK编码  

  219. deliverContent = new String(msgContent, "GBK");  

  220. // 处理DELIVER数据包的短信息ID  

  221. } else {  

  222. unioncomLog.error("编码格式错误!");  

  223. return "";  

  224. }  

  225. } else  

  226. return "";  

  227. return deliverContent;  

  228. } catch (UnsupportedEncodingException ex) {  

  229. unioncomLog.error("deal content error!" +
     ex.getMessage());  

  230. return "";  

  231. }  

  232. }  

上述内容就是Java中怎么实现 Socket通信,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 基于Java语言实现Socket通信的实例
  2. java如何实现Socket通信之单线程服务

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

java socket

上一篇:如何解决Android中Handler内存泄漏的问题

下一篇:怎么修改gazebo物理参数

相关阅读

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

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