notifyprocessor.java

来自「利用Java Socket写的一段通讯协议」· Java 代码 · 共 102 行

JAVA
102
字号
package com.ict.netcom2.net;

import java.net.*;
import java.io.*;

import com.ict.netcom2.message.*;
import com.ict.netcom2.kernel.*;

public class NotifyProcessor extends Thread {
    Socket skt;
    String ip;
    ActiveTaskDaemon2 daemon;
    DataInputStream in;
    PrintStream out;
    
    
    public NotifyProcessor(Socket skt, ActiveTaskDaemon2 d) {
        this.skt = skt;
        this.daemon = d;
		ip = skt.getRemoteSocketAddress().toString();
		ip = ip.substring(1, ip.indexOf(":"));
		System.out.println(ip);
    }

    
    public void run() {
        try {
        	in = new DataInputStream(skt.getInputStream());
			out = new PrintStream(new BufferedOutputStream(
					skt.getOutputStream()));
			
			MessageEncoder me = new MessageEncoder();
			
			// at least safe now...
			MessageDecoder2.decodeConnect(read());
			out.write(me.encodeConnectAck(0));
			out.flush();
        	
			Notify ntf = MessageDecoder2.decodeNotify(read());
			processNotify(ntf);
			
			/*
			// detect			
        	int ln = 512;
			byte[] b = new byte[ln];
			dis.read(b);
			for (int i=0; i<ln; i++) {
				String str = Byte.toString(b[i]);
				System.out.print(str+" ");
			}
			System.out.println();
			*/
			
			
			out.close();
			in.close();
			skt.close();
			
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
	/**
	 * Read a message from the opening inputstream.
	 * @return byte[] : The message without msg length.
	 */
	private byte[] read() {
		byte[] b = null;
		try {
			int len = in.readInt();
			//in.readInt();
			//in.readInt();
			
			if (len > 4) {
				b = new byte[len-4];
				in.read(b);
			}
			//TODO long length buffer MyByteBuffer
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return b;
	}
    
    private void processNotify(Notify ntf) {
    	switch (ntf.notifyType) {
    	
    	case CommandID.NetPro_TaskStatusNotify:
    		daemon.storeActiveTaskResult(ip, (TaskStatusNotify)ntf);
    		break;
    		
    		// TODO event notify
    	case CommandID.NetPro_EventNotify:
    	default:
    		System.out.println("todo tase: "
    				+CommandID.getType(ntf.notifyType));
    	}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?