Java Socket通信如何進(jìn)行通用服務(wù)器代碼編寫
Java Socket通信有很多的時(shí)候需要我們不斷的學(xué)習(xí)。方面效率雖然不及C與C++但它以靈活語(yǔ)言優(yōu)勢(shì),為大家廣為使用。 本文就對(duì)在使用java做通信方面程序時(shí)候應(yīng)改注意問(wèn)題做以說(shuō)明。
1.長(zhǎng)連接、短鏈接只是針對(duì)客戶端而言,服務(wù)器無(wú)所謂長(zhǎng)、短;
2.無(wú)論同步或者異步通信,發(fā)送之后務(wù)必要又響應(yīng)回復(fù),確認(rèn)收到,負(fù)責(zé)進(jìn)行一定范圍內(nèi)重發(fā),例如重發(fā)三次;
3.長(zhǎng)連接服務(wù)器與客戶端之間務(wù)必需要心跳探測(cè),由客戶端主動(dòng)發(fā)起;
4.短連接服務(wù)器通用代碼:
- 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 {
- //接受連接請(qǐng)求
- 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 : //錯(cuò)誤的命令字
- 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數(shù)據(jù)包的短信息ID
- } else {
- unioncomLog.error("編碼格式錯(cuò)誤!");
- return "";
- }
- } else
- return "";
- return deliverContent;
- } catch (UnsupportedEncodingException ex) {
- unioncomLog.error("deal content error!" +
ex.getMessage());- return "";
- }
- }
- }
以上就是對(duì)Java Socket通信的詳細(xì)介紹。希望大家有所幫助。
【編輯推薦】