本文共 2818 字,大约阅读时间需要 9 分钟。
java 多线程,,Socket,网络,流,并发,框架,已经讲完。 一个客户端实现的代码:
- import java.io.*;
- import java.nio.ByteBuffer;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import com.willfar.commons.net.ConcurrentQueue;
- import com.willfar.commons.net.IProcessClientData;
- import com.willfar.shantou.engine.protocol.ScadaIfcValidate;
- public class ProcessClientDataImpl implements
- IProcessClientData {
- private Log logger = LogFactory.getLog(ProcessClientDataImpl.class);
-
- private ConcurrentQueue dataQueue;
- private ByteArrayOutputStream streamData;
- private ByteArrayOutputStream tempStream;
- private ByteBuffer buf;
- private int requestCount;
- private String netAddress;
- private ScadaIfcValidate sv;
- public void run() {
- try {
- String s = "";
- boolean bool = true;
- sv = new ScadaIfcValidate();
- tempStream = new ByteArrayOutputStream();
- while (bool) {
- streamData = (ByteArrayOutputStream)dataQueue.deQueue();
- if (streamData != null) {
- int ll = streamData.size();
- if (ll == 3) {
- s = streamData.toString();
- if ("end".equals(s)) {
- logger.info("[" + requestCount + "],客户端发送数据结束.");
- bool = false;
- continue;
- }
- }
-
- streamData.writeTo(tempStream);
- ll = tempStream.size();
- if (ll < 3){
- continue;
- }
- byte[] b = tempStream.toByteArray();
-
- boolean bol = sv.isValid(b);
- if (bol) {
- logger.info("[" + requestCount + "],收到客户端["
- + netAddress+ "]数据,长度: " + tempStream.size()
- + " 字节,Fn内容:["+ sv.getFn() + "]");
- new Thread(new ProcessAcceptData(b)).start();
- }else{
-
- if(sv.getRemaining()>0){
- logger.info("数据总长: "+sv.getAllLength()+" 字节,收到: "
- + sv.getCurLength()+" 字节,等下一包数据...");
- continue;
- }else{
- logger.info("[" + requestCount + "],收到客户端[" + netAddress
- + "]数据,长度: " + tempStream.size() + " 字节,内容:[数据不完整]");
-
- this.getStringByByte(tempStream);
- tempStream.reset();
- tempStream.close();
-
- }
- }
- try {
- streamData.reset();
- streamData.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- } catch (IOException e1) {
- e1.printStackTrace();
- } finally {
- try {
- dataQueue.clear();
- dataQueue = null;
- tempStream.reset();
- tempStream.close();
- tempStream= null;
- streamData.reset();
- streamData.close();
- streamData=null;
- logger = null;
- sv =null;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- public void ProcessStreamData(ConcurrentQueue dataQueue, int requestCount, String netAddress) {
- this.dataQueue = dataQueue;
- this.requestCount = requestCount;
- this.netAddress = netAddress;
- }
-
- public void getStringByByte(ByteArrayOutputStream tempStream){
-
- if(tempStream!=null){
- StringBuffer bf = new StringBuffer();
- byte[] b = tempStream.toByteArray();
- for(int i=0;i<b.length;i++){
- bf.append(b[i]);
- }
- logger.info(bf.toString());
- bf = null;
- b = null;
- }
- }
- }
转载地址:http://jcnmd.baihongyu.com/