当前位置: 代码迷 >> J2SE >> 交互解决方案
  详细解决方案

交互解决方案

热度:248   发布时间:2016-04-24 15:29:00.0
交互
A向B说:hello     B    
B收到后向A说:hello     A  
要代码!

------解决方案--------------------
沙发
------解决方案--------------------
public interface EventHanlder{
public void handleEvent(String evt);
}

public class A implements EventHanlder{
public void handleEvent(String evt){
System.out.println( "Receive Event : " + evt);
}
public sayHello(){
B b = new B();
b.hello( "Hello B ");
}
public static void main(String args[]){
A a = new A();
a.sayHello();
}
}
public class B{
private EventHanlder a;
public B(EventHanlder a){ this.a = a;}

public void hello(String content){
System.out.println( "B Receive Event: " + content);
if(null != a) a.handleEvent( "Hello handler! ");
}
}
随手写的,没调过,意思就是使用回调
------解决方案--------------------
import java.io.*;
import java.net.*;
public class Server
{

ServerSocket server = null;
Socket you = null;
public Server()
{
try
{
server = new ServerSocket(2007);
while(true)
{
you = server.accept();
if(you != null)
new Thread(new Services(you)).start();
}
}catch(Exception e){}

}

public static void main(String args[])
{

new Server();
}

}

class Services implements Runnable
{
Socket you = null;
String data = null;
public Services(Socket you)
{
this.you = you;
}

public void run()
{
try
{
DataInputStream din = new DataInputStream(you.getInputStream());
DataOutputStream dout = new DataOutputStream(you.getOutputStream());
while(true)
{
data = din.readUTF();

if(data.equals( "exit "))
{
System.out.println(data);
break;

}

dout.writeUTF( "hello B ");
}
dout.close();
din.close();
you.close();
}catch(Exception e){}
}
}
  相关解决方案