ApacheMina:ObjectSerializationCodecFactory的例子

本文详细介绍了使用Java实现网络通信的服务器端和客户端代码,包括请求对象和响应对象的设计,以及服务器如何接收连接并处理客户端请求,最终通过实例展示了客户端如何与服务器进行交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 定义发送的RequestObject和返回的ResponseObject
RequestObject.java

public class RequestObject implements Serializable {

private static final long serialVersionUID = 8891436114296586399L;

private int id;
private String name;
private String description;
private String others;


public RequestObject(int id, String name, String description, String others) {
super();
this.id = id;
this.name = name;
this.description = description;
this.others = others;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getOthers() {
return others;
}
public void setOthers(String others) {
this.others = others;
}
@Override
public String toString() {
return "RequestObject [id=" + id + ", name=" + name + ", description="
+ description + ", others=" + others + "]";
}

}


ResponseObject.java

public class ResponseObject implements Serializable {


private static final long serialVersionUID = -6783592807728197249L;

private int id;
private String name;
private String value;
private String remarks;


public ResponseObject(int id, String name, String value, String remarks) {
super();
this.id = id;
this.name = name;
this.value = value;
this.remarks = remarks;
}


public int getId() {
return id;
}


public void setId(int id) {
this.id = id;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public String getValue() {
return value;
}


public void setValue(String value) {
this.value = value;
}


public String getRemarks() {
return remarks;
}


public void setRemarks(String remarks) {
this.remarks = remarks;
}


@Override
public String toString() {
return "ResponseObject [id=" + id + ", name=" + name + ", value="
+ value + ", remarks=" + remarks + "]";
}


}

2. 定义Server端的链接接收和业务处理机制
DemoObjectServer.java

public class DemoObjectServer {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {

final int PORT = 9123;

// objects used to listen for incoming connection
IoAcceptor acceptor = new NioSocketAcceptor();

// filters:
// 1. log all information
acceptor.getFilterChain().addLast("logger", new LoggingFilter());
// 2. translate binary or protocol specific data into message object
acceptor.getFilterChain().addLast("codec",new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));

// define the handler used to service client connections and the requests for the current time
acceptor.setHandler(new DemoObjectServerHandler());
//NioSocketAcceptor configuration: for the socket that will be used to accept connections from client
acceptor.getSessionConfig().setReadBufferSize(2048);
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

// define the handler class and bind the NioSocketAcception to a port
acceptor.bind(new InetSocketAddress(PORT));

}

}



DemoObjectServerHandler.java

public class DemoObjectServerHandler extends IoHandlerAdapter {

public DemoObjectServerHandler(){
super();
}

@Override
public void messageReceived(IoSession session, Object obj) throws Exception {
System.out.println("message received");

RequestObject ro = (RequestObject) obj;
System.out.println("request body:" + ro.toString());

String _name = "request_" + ro.getId();
String _remarks = "description is " + ro.getDescription() + ", and others is " + ro.getOthers();
ResponseObject rpo = new ResponseObject(ro.getId(),_name, ro.getName(), _remarks);
session.write(rpo);

}

@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
super.exceptionCaught(session, cause);

session.close(true);
}


}


3. 定义Client端的链接和业务处理机制
DemoObjectClient.java

public class DemoObjectClient {

/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {

// create a connector
NioSocketConnector connector = new NioSocketConnector();
//create a fitler chain
connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
connector.getFilterChain().addLast("logger", new LoggingFilter());

// create iohandler
//DemoTimeClientHandler handler = new DemoTimeClientHandler("i am jeanjeanfang, hello dear!");
connector.setHandler(new DemoObjectClientHandler());

//connector.setHandler(new ClientSessionHandler(values));

// bind to server
IoSession session;
for (;;) {

try {

ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 9123));
future.awaitUninterruptibly();
session = future.getSession();
break;
} catch (RuntimeIoException e) {
System.err.println("Failed to connect.");
e.printStackTrace();
Thread.sleep(5000);
}
}

// wait until the summation is done
session.getCloseFuture().awaitUninterruptibly();

connector.dispose();


}



}


DemoObjectClientHandler.java

public class DemoObjectClientHandler extends IoHandlerAdapter {

@Override
public void exceptionCaught(IoSession session, Throwable t)
throws Exception {
super.exceptionCaught(session, t);
session.close(true);
}

@Override
public void messageReceived(IoSession session, Object obj) throws Exception {
System.out.println("message received");

ResponseObject ro = (ResponseObject) obj;
System.out.println("received obj:" + ro.toString());

session.close(true);


}

@Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("session opened");

RequestObject ro = new RequestObject(101,"name","des11","others...");

session.write(ro);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值