当前位置:编程学习 > JAVA >>

javaSocket与C通信

前段时间写了个web端与C服务端之间的通信不过用的是短连接 非堵塞的方式,一直想使用长连接,使tomcat启动的时候就和C服务端进行通信,但是一直没找到方法希望je的朋友能给点思路。先来看我现在的具体实现
通信的核心类
public class newsSockBase   
{  
    private SocketChannel sc;    
    private final int MAX_LENGTH = 8192;    
    private ByteBuffer r_buff ;    
    private ByteBuffer w_buff ;    
    private static String host ;    
    private static int port;    
 
    int     sendBufTotalLen;  
    int     sendBufLen;  
    int     sendBufStart;  
    byte[]  sendBuf;  
      
    int     recvBufTotalLen;  
    int     recvBufLen;  
    int     recvBufStart;  
    byte[]  recvBuf;  
      
    int     timeout;  
    String  msg;  
      
    public newsSockBase()  
    {  
        r_buff = ByteBuffer.allocate(MAX_LENGTH);    
        w_buff = ByteBuffer.allocate(MAX_LENGTH);   
          
        sendBufTotalLen = MAX_LENGTH;  
        sendBufLen = sendBufStart = 0;  
        sendBuf = new byte[MAX_LENGTH];  
          
        recvBufTotalLen = MAX_LENGTH;  
        recvBufLen = recvBufStart = 0;  
        recvBuf = new byte[MAX_LENGTH];  
          
        timeout = 6;  
    }  
      
    public void setIPandPort(String str,int pt)  
    {  
        host = str;  
        port  = pt;  
    }  
      
    //这两个函数一定要注意 形参是基类 而实际传入的参数是子类,到时候也是调用子类的参数来做  
    public void getBufFrompara(InewsDetail nD)  
    {  
        int len = nD.encode(sendBuf, sendBufStart, sendBufTotalLen-sendBufStart-sendBufLen);  
          
        sendBufLen += len;  
          
    }  
      
    public int decodeBufToPara(InewsDetail nD)  
    {  
        int len = nD.decode(recvBuf, recvBufStart, recvBufLen);  
        if (len>0)   //解码正确的时候才做  
        {  
            recvBufLen -= len;  
            recvBufStart += len;          
        }  
          
        return len;   
    }  
      
    public void start(InewsDetail nD)  
    {      
      
        //这里需要先根据传入的参数来  
        getBufFrompara(nD);  
          
        try {    
            InetSocketAddress addr = new InetSocketAddress(host, port);    
            // 生成一个socketchannel    
            sc = SocketChannel.open();    
            sc.configureBlocking(false);//   
            // 连接到server    
            sc.connect(addr);    
            while (!sc.finishConnect())    
                ;    
            System.out.println("connection has been established!…");    
 
           // while (true)   
            {    
                // 回射消息    // 复位,清空              
                w_buff.clear();    
                w_buff.put(sendBuf,sendBufStart,sendBufLen);    
                w_buff.flip();   // 转到最开始   
 
 
                // 发送消息    
                while (w_buff.hasRemaining())    
                    sc.write(w_buff);    
                w_buff.clear();  
补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,