通过Socket实现进程间异步通讯(二)

第二步:写一个socket异步通讯类SignalSocketThread

package com.hode.thread;

/**
 * @author 泰伯子仪
 *
 * 需要使用SignalSocketThread中Socket客户端获得异步通信的对象必须继承此接口
 */
public interface DealWith
{
   public void dealwith();
}

 

package com.hode.thread;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author 泰伯子仪
 *
 */
public class SignalSocketThread extends Thread
{

    public static int PORT = 8881;
   
    private static String CanIWorkNow = "CanIWorkNow";
   
    private static String YouCanWork = "YouCanWork";
   
    private static String MyWorkIsCompleted = "MyWorkIsComplete";
   
    private static String IGetYouMessage = "IGetYouMessage";
   
    private static String Shutdown = "Shutdown";
   
    private CommThread commThread = null;

    /**
     *
     */
   
    public SignalSocketThread()
    {
        super("SignalSocketThread");
    }
   
    public SignalSocketThread(int port)
    {
        super("SignalSocketThread");
        PORT = port;
    }
   
    public void threadStart()
    {
        start();
    }
   
    public void run()
    {
        ServerSocket();  
    }
   
    public void ServerSocket()
    {
        ServerSocket s = null;
        Socket socket = null;
        try
        {
            InetAddress addr = InetAddress.getByName("localhost");
            s = new ServerSocket(PORT, 1, addr);
            System.out.println("/nStarted: " + s);
            while (true)
            {
             // Blocks until a connection occurs:
                System.out.println("/n打开端口"+PORT);
             socket = s.accept();
             System.out.println("Connection accepted: " + socket);
             BufferedReader in = new BufferedReader(
                          new InputStreamReader(socket.getInputStream()));
             // Output is automatically flushed
             // by PrintWriter:
             PrintWriter out = new PrintWriter(new BufferedWriter(
                                 new OutputStreamWriter(socket.getOutputStream())), true);
           
                String strIn = null;
                while((strIn=in.readLine()) != null)
                {
                    System.out.println("通讯过程: ");
                 if(strIn.equals(Shutdown))
                 {
                     System.out.println("    [收到]: " + Shutdown);
                     return;
                 }  
                 else if (strIn.equals(CanIWorkNow))
                 {
                     System.out.println("    [收到]:" + CanIWorkNow);
                     waitThread();
                     System.out.println("    [发送]: " + YouCanWork);
                     out.println(YouCanWork); 
                 }
                 else if (strIn.equals(MyWorkIsCompleted))
              {
                     System.out.println("    [收到]:" + MyWorkIsCompleted);
                     workThread();
                     System.out.println("    [发送]: " + IGetYouMessage);
                     out.println(IGetYouMessage);
                 }
                }
                socket.close();
            }
        }
        catch(IOException e){}
        finally
        {
            try
            {
                // Always close the two sockets...
                if(socket != null)
                {
                 System.out.println("closing...");
                 socket.close();
                }
                if(s != null)
                {
                 s.close();
                 System.out.println("服务端 closed");
                }
            }
            catch(IOException e){}
        }
    }
   
    public boolean ClientSocket(String question,String answer)
    {
        boolean bool = false;
        Socket socket = null;
        try
        {
            InetAddress addr = InetAddress.getByName("localhost");
            System.out.println("/naddr = " + addr);
            socket = new Socket(addr,PORT);
            System.out.println("socket = " + socket);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket
                    .getInputStream()));
            // Output is automatically flushed
            // by PrintWriter:
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())), true);
           
            System.out.println("/n通讯过程:");
            out.println(question);
            System.out.println("    [发送]:" + question);
           
            String strIn = in.readLine();
            if(strIn != null)
            {
             System.out.println("    [收到]: " + strIn);
             if(strIn.equals(answer))
             {
                 bool = true;
             }
            }
        }
        catch(ConnectException e)
        {
            System.out.println("异常:"+PORT+"服务不存在");
        }
        catch(IOException e){}
        finally
        {        
            try
            {
                if(socket != null)
                {
                 // Always close the two sockets...
                 System.out.println("closing...");
                 socket.close();
                 System.out.println("客户端 closed");
                }
            }
            catch(IOException e){}
        }
        return bool;
    }
   
    public boolean Shutdown()
    {
        return ClientSocket(Shutdown,"");
    }
   
    public boolean CanIWork()
    {
        return ClientSocket(CanIWorkNow,YouCanWork);
    }
   
    public boolean MyWorkIsCompleted()
    {
        return ClientSocket(MyWorkIsCompleted,IGetYouMessage);
    }
   
    public void serverBind(CommThread commThread)
    {
        this.commThread = commThread;
    }
   
    public void waitThread()
    {
        while(commThread.getWork()){}
        commThread.setWait(true);
        System.out.println("isWait = true");
    }
   
    public void workThread()
    {
        commThread.setWait(false);
    }
   
    public void ClientBind(DealWith dealWith)
    {
        if (CanIWork())
        {
            dealWith.dealwith();          
            int count = 0;
            while (!MyWorkIsCompleted())
            {
                count++;
                if (count >= 100)
                {
                    System.err.println("/n响应超时");
                    break;
                }
            }
        }
    }
   
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值