多线程多端口Socket服务端客户端代码 java

来源:互联网 发布:电子标书制作软件 编辑:程序博客网 时间:2024/06/06 02:15

服务端代码

GPRSServer.java 创建服务

GPRSHander.java 调用GPRSServer来创建多线程多端口服务

**************************************************************GPRSServer.java 结束************************************************************

/*
* @(#)GPRSServer.java 1.0 11/06/14
*
* Copyright 2011 Emerson NetWork Power COM.,TLD, Inc. All rights reserved.
* Emerson PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.emerson.upscoutersrvr.protocol.communication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.emerson.upscoutersrvr.util.CommonDAO;

/**
* <P>
*   Title: GPRS服务端类
* </P>
* <P>
*   Descriptoin: 主要用来接收GPRS上报上来的几种数据,包括解析监听
* </P>
* <p>
*   Copyright:Copyright (c) EMERSON 2011 All rights reserved
* </p>
* <P>
*   Commpany : EMERSON NEWWORK POWER
* </P>
*
* @author lumou
* @version 1.0
*
*/
public class GPRSServer extends CommonDAO implements Runnable{

//------------------------------------------------------------------私有属性
/**
  * 日志
  */
private Log log = LogFactory.getLog(GPRSServer.class);

/**
  * 服务器地址
  */
private String hostAdd;

/**
  * 服务器端口
  */
private int hostPort;

/**
  * 服务器Socket
  */
private ServerSocket server;

/**
  * 管理本地线程
  */
private Thread thead;
//------------------------------------------------------------------构造函数

/**
  * <P>构造线程来处理设备</P>
  *
  * @param areaId
  *            设备服务端所需要的端口
  */
public GPRSServer(int areaId){
  if(thead == null){
   thead = new Thread(this);
  }
  try {
   hostPort = areaId+11024;
   server = new ServerSocket(hostPort);
   log.info("端口:["+hostPort+"]的服务端创建OK,等待客户端连接……");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   log.error("端口:["+hostPort+"]的服务器启动异常……");
  }
}

//------------------------------------------------------------------业务方法

/**
  * 初始化程序属性
  */
public void init(){
  try {
   Map map = (Map) super.executeQueryForObject("CommData.selectGPRSPort", null);
   hostPort = map.get("PORT_TX") == null ?
     4320 : Integer.parseInt(map.get("PORT_TX").toString());
   hostAdd = map.get("SMTPSERVER_TX") == null ?
     "127.0.0.1" : map.get("SMTPSERVER_TX").toString();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   log.info("初始化程序属性异常",e);
  }
}

/**
  * 启动本线程
  */
public void start(){
  thead.start();
}

/**
  * 关闭本线程
  */
public void stop(int areaId){
  hostPort = areaId+11024;
  thead.stop();
}
/**
  * 主处理方法
  */
public void run() {
  // TODO Auto-generated method stub
  try {
   while(true){
    if(server != null){
     Socket socket = server.accept();
     if(socket != null){
      log.info("端口:["+hostPort+"]的客户端连接成功");
      BufferedReader bis = new BufferedReader(new InputStreamReader(
        socket.getInputStream()));
      OutputStream osm = socket.getOutputStream();
      osm.write("Server say: Hello EveryOne!".getBytes());
      System.out.println(bis.readLine());
      osm.close();
      bis.close();
      socket.close();
     }
    }
    Thread.sleep(1000l*1);
   }
  
  //解析数据
  } catch (Exception e) {
   // TODO Auto-generated catch block
   log.error("端口:["+hostPort+"]的服务器运行异常……",e);
  } finally {
   try {
    if(null != server){
     server.close();
    }
   } catch (IOException e) {
    // TODO Auto-generated catch block
    log.error("端口:["+hostPort+"]关闭服务器运行异常……",e);
   }
  }
}

/**
  * <P>解析数据平且入库</P>
  * @param obj
  */
public void parseData(String obj){
 
}


//---------------------------------------------------------getter,setter方法


}

**************************************************************GPRSServer.java 结束************************************************************

GPRSHander.java

**************************************************************GPRSHander.java ************************************************************

/*
* @(#)GPRSHander.java 1.0 11/06/22
*
* Copyright 2011 Emerson NetWork Power COM.,TLD, Inc. All rights reserved.
* Emerson PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.emerson.upscoutersrvr.protocol.communication;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.emerson.upscoutersrvr.util.CommonDAO;

/**
* <P>
*   Title: GPRS线程监控类
* </P>
* <P>
*   Description: 主要通过GPRS处理历史数据,实时数据,告警数据
* </P>
* <P>
*   Copyright: Copyright(C) EMERSON 2011 All rights reserved
* </P>
* <P>
*   Company : EMERSON NETWORK POWER COM,. TLD
* </P>
* @author G92201d
* @version 1.0  2011-06-22
*
*/
public class GPRSHander extends CommonDAO implements Runnable {

//-----------------------------------------------------------------私有属性
/**
  *<P>日志</P>
  */
private Log log = LogFactory.getLog(GPRSHander.class);

/**
  * 本地线程管理
  */
private Thread th;

/**
  * 本地线程状态
  */
private boolean keepState;

//-----------------------------------------------------------------业务方法
/**
  * <P>主处理函数</P>
  */
public void run() {
  // TODO Auto-generated method stub
  /*
   * 查询所有站点,每个站点生成一个socket服务端
   * */
  try {
    List list = super.executeQueryForList("CommData.selectArea", null);
   
    if(null != list){
     int count = list.size();
     for (int i = 0; i < count; i++) {
      Map map = (Map) list.get(i);
      int areaId = Integer.parseInt(map.get("areaId") == null ?
        "11024" : map.get("areaId").toString());
     
      //创建服务线程
      GPRSServer gs = new GPRSServer(areaId);//每个设备启动一个线程,启动一个端口
      gs.start();
     }
      th.sleep(1000l*1);
    }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   keepState = true;
   log.error("数据连接异常!",e);
  }catch (InterruptedException e) {
   // TODO Auto-generated catch block
   log.error("线程休眠异常!",e);
  }
}

/**
  * <P>启动本线程</P>
  */
public void start(){
  th = new Thread(this);
  th.start();
  keepState = false;
}

/**
  * <P>停止本线程</P>
  */
public void stop(){
  if(th != null){
   th.stop();
   keepState = true;
  }
}

public static void main(String[] args) {
  GPRSHander gh = new GPRSHander();
  gh.start();
}
}

**************************************************************GPRSHander.java 结束************************************************************

客户端代码:

Client.java

**************************************************************Client.java 开始************************************************************

package com.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

/**
  * @param args
  */
public static void main(String[] args) {
  // TODO Auto-generated method stub
  Socket socket = null;
  try {

   int i = 0;
   socket = new Socket("localhost", 11037);
   OutputStream os = socket.getOutputStream();
   InputStream is = socket.getInputStream();

   os.write("clent say: hello how are you1?".getBytes());
   os.write("clent say: hello how are you2?".getBytes());
   os.write("clent say: hello how are you3?".getBytes());

   byte[] bt = new byte[1024];
   is.read(bt, 0, bt.length);
   os.close();
   is.close();
   System.out.println(new String(bt, 0, bt.length));
  
   i++;
   Thread.sleep(300);

  } catch (UnknownHostException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
}

}

**************************************************************Client.java 结束************************************************************

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 腿又粗又短怎么办 腿又短又粗怎么办 因跑步小腿变粗怎么办 健身后小腿变粗怎么办 打非洲鼓打的手疼怎么办 无塔供水压力小怎么办 家用增压水塔压力不稳定怎么办 蝴蝶耳堵比较紧怎么办 跑步机踏板坏了怎么办 遥控器电池没电了怎么办 空调遥控器电池没电了怎么办 想要自慰家里没有情趣用品怎么办 对政协提案的答复有意见怎么办 邻居在自建房养殖鳖怎么办 江桥全民健身卡怎么办 南翔全民健身卡怎么办 椭圆机皮带断了怎么办 不小心扭腰了怎么办 扭腰之后腿疼怎么办 扭腰怎么办吃什么补 湖州奥体中心怎么办卡 学车把教练投诉了怎么办 白球鞋鞋边发黄怎么办 公务员体检时心跳过快怎么办 老人心脏跳得慢怎么办 银行月限额10万怎么办 跑步后迎面骨疼怎么办 跑步时迎面骨疼怎么办 爬了楼梯小腿疼怎么办 走路走太多小腿酸痛怎么办 微信转账月限额怎么办 运动后小腿骨疼怎么办 用单杠练腹肌晃怎么办 一跑步小腿就紧怎么办 小腿一跑步就痛怎么办 单杠屈臂悬垂身体摆动怎么办 脸上被打了紫了怎么办 王者荣耀队友太坑怎么办 大脸不想戴泳帽怎么办 脐带掉了有血怎么办 颈椎不小心扭了怎么办