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){}
}
}