`

即时通信学习笔记

阅读更多

下载安装文件
openfire_3_6_4.exe
spark_2_5_8_exe.exe
org.jivesoftware.smack_3.1.0.jar


源代码下载路径
http://svn.igniterealtime.org/svn/repos/openfire/trunk


搭建openfire服务器
C:\WINDOWS\system32\drivers\etc\hosts文件,增加一新行:
127.0.0.1 cn.yue.com


安装
openfire_3_6_4.exe


创建openfire运行时所需数据库
C:\Program Files\Openfire\resources\database
我们使用mysql
找到openfire_mysql.sql
创建数据库


注:
如果使用sqlserver数据库,需要添加sqlserver 的jdbc驱动包放到/lib目录下




运行/bin/openfire.exe
launch admin---> 简体中文continue-->输入域名(cn.yue.com)
--->标准数据库连接-->数据库配制--->初始设置-->创建管理员账号--->完成




查看ofuser就可以看到同刚才创建的管理员账号


重启openfire后,登陆管理页面


windows 服务端反搭建完成
==================================================================
搭建客户端测试openfire服务器


连接openfire服务器
注册用户
在不同有基于xmpp协议定的客户端进行添加好友和发送即时消息




安装spark2.5.8.exe
======================================================================
即时消息android 客户端
下载asmack-2010.05.07.jar
新建工程
1 登录
/**
* 联接服务器工具类
*
* @time 下午2:44:28
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class ConnectUtil {
private static XMPPConnection connection = null;


public ConnectUtil() {
}


public static void openConnection() {
ConnectionConfiguration configuration = new ConnectionConfiguration("192.168.1.5", 5222);
connection = new XMPPConnection(configuration);
try {
connection.connect();
} catch (XMPPException e) {
e.printStackTrace();
Mylog.i("tag", "联接服务器失败!" + e.toString());
}
}


/**
* 建立联接 取得connection对象
*
* @return
*/
public static XMPPConnection getConnection() {
if (connection == null) {
openConnection();
}
return connection;
}


/**
* 关闭联接
*/
public static void closeConnection() {
if (connection != null) {
connection.disconnect();
connection = null;
}
}
}




/**
* 用户登录
*
* @time 下午10:00:42
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class LoginActivity extends BaseActivity implements OnClickListener {
private EditText etxt_userName;
private EditText etxt_pwd;


private UserService userService;
private User user;
private SharedPreferences sp;
private ProgressDialog progressDialog;
private String userName, pwd;
private boolean ispswd = false;
private String state;
private Handler handler = new Handler() {


@Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
if (msg.what == Constants.LOGIN_SUCESS) {
Mylog.i("tag", "--------------------");
// 进入主页面
Intent intent = new Intent(state);
intent.putExtra("choseNum", Constants.TALKLIST_SHOW);
sendBroadcast(intent);


// 保存用户信息
sp = getSharedPreferences("survey", Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("userName", etxt_userName.getText().toString().trim());
editor.putString("pwd", etxt_pwd.getText().toString().trim());
editor.putBoolean("ispswd", ispswd);
editor.commit();


} else if (msg.what == Constants.LOGIN_FAILED) {
// 清空信息,登录失败
etxt_pwd.setText("");
etxt_userName.setText("");
etxt_userName.requestFocus();
Toast.makeText(LoginActivity.this, "用户名/密码错误!", Toast.LENGTH_LONG).show();


}
}


};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
findView();
init();
// 是否自动登录
autoCheckin();
}


/**
* 初始化方法
*/
private void init() {
state = getIntent().getAction();


user = new User();
userService = new UserServiceImpl();
// 取得用户登录信息


sp = getSharedPreferences("survey", Context.MODE_PRIVATE);
String userName = sp.getString("userName", "test3");
String pwd = sp.getString("pwd", "123456");
etxt_userName.setText(userName);
etxt_pwd.setText(pwd);
user.setEmail(userName);
user.setPassword(pwd);
}


@Override
protected void onResume() {
setClazz(LoginActivity.class);
super.onResume();
}


/**
* 实例化控件
*/


@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_btn_reg:// 用户注册
reg();


break;


case R.id.login_btn_checkin:// 登录
login();
break;
}
}


private void findView() {
etxt_userName = (EditText) this.findViewById(R.id.login_etxt_username);
etxt_pwd = (EditText) this.findViewById(R.id.login_etxt_pwd);


this.findViewById(R.id.login_btn_checkin).setOnClickListener(this);
this.findViewById(R.id.login_btn_reg).setOnClickListener(this);


}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Mylog.i("tag", "================" + resultCode);


if (resultCode == RESULT_FIRST_USER) {
Bundle bundle = data.getExtras();
// 回显用户信息
etxt_userName.setText(bundle.getString("userName"));
etxt_pwd.setText(bundle.getString("pwd"));
}
super.onActivityResult(requestCode, resultCode, data);
}


/******************** 业务方法 ********************************************************************/
/**
* 登录
*/
private void login() {
if (inputCheck()) {
progressDialog = ProgressDialog.show(LoginActivity.this.getParent().getParent(), "请稍等", "用户登录中...", true);
new LoginThread().start();
}


}


/**
* 检查用户输入合法性
*/


private boolean inputCheck() {
userName = etxt_userName.getText().toString();
if (!ValidateUtil.isValidate(userName)) {
Toast.makeText(LoginActivity.this, "请输入email!", Toast.LENGTH_SHORT).show();
etxt_userName.requestFocus();
return false;
}
pwd = etxt_pwd.getText().toString();
if (!ValidateUtil.isValidate(pwd)) {
Toast.makeText(LoginActivity.this, "请输入密码!", Toast.LENGTH_SHORT).show();
etxt_pwd.requestFocus();
return false;
}
user.setEmail(userName);
user.setPassword(pwd);
return true;
}


/**
* 注册
*/
private void reg() {
Intent intent = new Intent(state);
intent.putExtra("choseNum", Constants.REG_SHOW);
sendBroadcast(intent);
Toast.makeText(LoginActivity.this, "clicked register!", Toast.LENGTH_LONG).show();


// Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
// startActivityForResult(intent, Constants.LOGIN_RECORDER);
}


/**
* 用户登录线程
*/
private class LoginThread extends Thread {


@Override
public void run() {
xmppLogin();
}


}


/**
* 登录xmpp服务器
*/
private void xmppLogin() {
try {
Mylog.i("tag", "username:" + user.getEmail() + " pwd:" + user.getPassword());
// 登录服务器
ConnectUtil.getConnection().login(user.getEmail(), user.getPassword());
// 设置用户状态(在线状态)
Presence presence = new Presence(Presence.Type.available);
ConnectUtil.getConnection().sendPacket(presence);
handler.sendEmptyMessage(Constants.LOGIN_SUCESS);
} catch (XMPPException e) {
e.printStackTrace();
ConnectUtil.closeConnection();
handler.sendEmptyMessage(Constants.LOGIN_FAILED);
}


}


// TODO
@SuppressWarnings("unused")
private void Testlogin() {
// 调用userService登录
String result = userService.getEntity(user);
Mylog.i("tag", "result++++++++++++++++++++++" + result);
if (ValidateUtil.isValidate(result)) {
if (result.equals("success")) {
handler.sendEmptyMessage(Constants.LOGIN_SUCESS);
} else {
handler.sendEmptyMessage(Constants.LOGIN_FAILED);
}
}
}


@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
LocalUtils.exitConfirm(LoginActivity.this.getParent().getParent());
break;
}
return true;
}





/**
* 自动登录
*/
private void autoCheckin() {
if (ValidateUtil.isValidate(user.getEmail()) && ValidateUtil.isValidate(user.getPassword())) {
login();
}
}
}














======================================================================
mina下载路径
http://mina.apache.org/downloads.html
apache-mina-2.0.7-bin


传送字符串的简单c/s


所需jar包
mina-core-2.0.7.jar
slf4j-api-1.5.8.jar
slf4j-nop-1.5.8.jar




服务器端
示例代码如下
/**
* mina服务器端
*
* 启动服务器的主类
*
* @time 下午3:17:08
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class MinaServer {


/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// 创建一个非阻塞的sserver端socket
SocketAcceptor acceptor = new NioSocketAcceptor();
// 创建接收数据的过滤器
DefaultIoFilterChainBuilder chainBuilder = acceptor.getFilterChain();
// 过滤器读取数据
chainBuilder.addLast("myChain", new ProtocolCodecFilter(new TextLineCodecFactory()));
// 设定服务器端的消息处理器
acceptor.setHandler(new SampleMinaServerHandler());
int bindPort = 9988;
// 服务器端邦定的端口
acceptor.bind(new InetSocketAddress(bindPort));


System.out.println("minaServer is starting!" + bindPort);
}
}


/**
* 消息处理器
*
* @time 下午3:18:57
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class SampleMinaServerHandler extends IoHandlerAdapter {
private int count = 0;


/**
* 客户端连接成功
*/
@Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("incomming client:" + session.getRemoteAddress());
}


/**
* 客户端关闭联接
*/
@Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("one client disconnect!");
}


/**
* 接收到客户端发送的消息
*/
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
String msg = (String) message;
System.out.println("接收到客户端消息:" + msg);
// 回送消息给客户端
session.write(msg + count);
count++;
}


}






测试服务器端程序


命令行模式:
telnet localhost 9988
helloworld


服务器端信息
minaServer is starting!9988
incomming client:/127.0.0.1:31185
接收到客户端消息:hello world




代码实现客户端程序
/**
* mina客户端
*
* @time 下午4:04:27
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class MinaClient {


/**
* @param args
*/
public static void main(String[] args) {
//
NioSocketConnector connector = new NioSocketConnector();
// 创建过滤器
DefaultIoFilterChainBuilder chain = connector.getFilterChain();
// 设置过滤器读取数据方式
chain.addLast("myChain", new ProtocolCodecFilter(new TextLineCodecFactory()));


// 设置客户端的消息处理器
connector.setHandler(new SampleMinaServerHandler());
// 设置超时时间
connector.setConnectTimeout(3000);
// 连接到服务器
ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 9988));
future.awaitUninterruptibly();
future.getSession().getCloseFuture().awaitUninterruptibly();
connector.dispose();
}


}




/**
* 客户端消息处理器
*
* @time 下午3:18:57
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class SampleMinaServerHandler extends IoHandlerAdapter {
private int count = 0;


/**
* 客户端连接成功
*/
@Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("incomming client:" + session.getRemoteAddress());
session.write("client ====come on !");
}


/**
* 客户端关闭联接
*/
@Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("client ====one client disconnect!");
}


/**
* 接收到客户端发送的消息
*/
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
String msg = (String) message;
System.out.println("接收到服务器端消息:" + msg);
// 回送消息给客户端
session.write(msg + count);
count++;
}


}


======================================================================



















分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics