Java Socket通信如何进行通用服务器代码编写

开发 后端
Java Socket通信需要我们不断的进行相关问题的学习,下面我们就看看如何才能更好的进行有关问题解决方案。希望大家有所帮助。

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

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服务端具体命令编写
  3. Java Socket通讯如何进行客户端的信息通信
  4. Java Socket通讯客户端代码编写教程
  5. Java Socket通讯实际操作手册
责任编辑:张浩 来源: 博客园
相关推荐

2010-03-18 20:00:35

Java socket

2010-03-16 10:32:36

Java线程拨号器

2010-02-03 13:55:51

Python 代码

2010-03-16 14:41:06

Java Runnab

2011-07-25 10:48:34

服务器虚拟服务器

2010-03-09 18:14:55

Python sock

2010-03-16 13:47:48

Java多线程服务器

2011-07-14 14:58:19

网络服务器配置服务器

2009-08-21 16:13:45

代理服务器设置迅雷

2010-03-18 17:39:46

Java Socket

2010-06-02 18:51:35

搭建SVN服务器

2011-07-04 10:20:25

服务器云时代

2011-10-26 11:21:47

服务器虚拟化存储管理

2011-06-29 10:06:23

Linux服务器优化

2017-08-04 10:47:20

2018-07-20 10:12:27

租用服务器速度测试

2010-03-19 09:26:34

Java Socket

2010-03-19 15:01:23

Java Socket

2011-08-02 16:46:33

FoxmailServ邮件服务器域管理

2016-09-14 21:44:50

JavascriptreactJsjsx
点赞
收藏

51CTO技术栈公众号