C语言 棋子游戏 图形处理
(1)你可以选择两种玩法,与电脑,或对局
(2)游戏开始时,有两种选择但只能玩对局的,要不右边的棋子不能
被选中,(是电脑的棋子)
(3)想操纵左边棋子的朋友可以按 E,D,S,F键移动一个矩形光标.
光标包围自己的棋子时,可以按空格键,选中它,然后在一个没有
棋子的点按上空格键,即可移动棋子,小心!!!不要对方把您的棋
子吃掉了,如果您把对方的棋子都吃掉了,或者对方的棋子被您的棋
子包围了,使对方不能移动自己的棋子了,您就赢了这盘棋反之,
则输了这盘棋.
操纵右边棋子的朋友,可按 Up,Down,Left,Right键移动棋子,按Enter
键选中棋子.
(4)游戏规则:
1.您不能操纵对方的棋子
2.移动棋子时,起点到终点所成的直线中不能有其它任何棋子,否则
就不能移动棋子.
3.起点到终点形成的直线必须是棋盘上的某条直线,否则不能移动
棋子.
4.吃掉对方棋子的情况(满足如下关系)
A B A
B A B
则棋子B(第一种情况吃掉一个棋子,第二种情况吃掉两个棋子)被吃掉了
(5)可按Esc键退出游戏
GB2312 汉字基本库
1.根据给定汉字值得到汉字拼音,五笔,笔顺,和笔画数
2.要所给定汉字的索引值得到汉字拼音,五笔,笔顺,和笔画数
3.可直接导入GB2312Helper.jar包使用,或修改代码实现更多功能
示例
public static void main(String args[]) {
GB2312Helper helper = GB2312Helper.singleton();
GB2312Record record = helper.getRecord('我');
if (record != null) {
System.out.println(record.getValue() + " " + record.getPingyin() + " " + record.getBishun());
} else {
System.out.println("null");
}
String info = "测试汉字拼音和五笔";
GB2312Record rcds[] = helper.getRecords(info);
String pingyin = helper.getPingyin(rcds);
System.out.println(pingyin);
}
输出:
我 wo3 3121534
ce4shi4han4zi4pin1yin1he2wu3bi3
GBK 汉字基本库 笔画 笔顺
GBK汉字库
1.整合6763个GB2312个汉字
2.整合GBK/3,GBK/4协议共21003个汉字
3.五笔,拼音,和汉字结构等基本属性
4.已生成了GBKHelper.jar包,可直接使用或修改源代码实现更多功能
示例程序:
long lasttick = System.currentTimeMillis();
GB2312Helper gb2312Helper = GB2312Helper.singleton();
String info1 = "测试汉字拼音和五笔";
CharacterRecord recs1[] = gb2312Helper.getRecords(info1);
String rlt1 = gb2312Helper.getPingyin(recs1);
long curtick = System.currentTimeMillis();
System.out.println("=======GB2312用时:=======" + (curtick - lasttick));
System.out.println(rlt1);
System.out.println("size=" + GB2312Helper.singleton().getRecordSize());
long lasttick2 = System.currentTimeMillis();
GBKHelper gbkHelper = GBKHelper.singleton();
String info2 = "测试汉字拼音和五笔 龍齏";
CharacterRecord recs2[] = gbkHelper.getRecords(info2);
String rlt2 = gbkHelper.getPingyin(recs2);
long curtick2 = System.currentTimeMillis();
System.out.println("=======GBK用时:=======" + (curtick2 - lasttick2));
System.out.println(rlt2);
System.out.println("size=" + GBKHelper.singleton().getRecordSize());
=======GB2312用时:=======281
ce4shi4han4zi4pin1yin1he2wu3bi3
size=6763
=======GBK用时:=======140
ce4shi4han4zi4pin1yin1he2wu3bi3 long2ji1
size=20923
android 日期选择器
package com.custom.dtselector.dialog;
import java.util.Calendar;
import com.custom.dtselector.NumericWheelAdapter;
import com.custom.dtselector.OnWheelChangedListener;
import com.custom.dtselector.WheelView;
import com.demo.dtselector.R;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class DateSelectorDialog extends BaseDialog {
private static final int START_YEAR = 1900;
private static final int END_YEAR = 2100;
private int tdYear = 0;
private int tdMonth = 0;
private int tdDay = 0;
private WheelView wlvYear = null;
private WheelView wlvMonth = null;
private WheelView wlvDay = null;
private NumericWheelAdapter yearAdapter = null;
private NumericWheelAdapter monthAdapter = null;
private NumericWheelAdapter dayAdapter[] = new NumericWheelAdapter[4];
private NumericWheelAdapter curDayAdapter = null;
private int sltYear = 0;
private int sltMonth = 0;
private int sltDay = 0;
private String strSltYear = "";
private String strSltMonth = "";
private String strSltDay = "";
/**回调接口*/
private OnSelectDateEvent resultEvent = null;
@Override
public void init(Context context) {
// TODO Auto-generated method stub
this.context = context;
dialog = new Dialog(this.context, R.style.CustomDialog);
dialog.setContentView(R.layout.date_selector);
wlvYear = (WheelView)dialog.findViewById(R.id.date_selector_year);
wlvMonth = (WheelView)dialog.findViewById(R.id.date_selector_month);
wlvDay = (WheelView)dialog.findViewById(R.id.date_selector_day);
Button btnSelect = (Button)dialog.findViewById(R.id.btn_date_yes);
btnSelect.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
selectDate();
}
});
initCurDate();
initAdapters();
//对话框隐藏后,调用回调事件
dialog.setOnCancelListener(new OnCancelListener(){
@Override
public void onCancel(DialogInterface arg0) {
// TODO Auto-generated method stub
if (resultEvent != null) {
resultEvent.onSelectDateResult(sltYear, sltMonth, sltDay);
}
}
});
}
@Override
public void update(Object obj) {
// TODO Auto-generated method stub
}
/**
* 设置回调事件
* @param event
*/
public void setOnSelectDateEvent(OnSelectDateEvent event) {
this.resultEvent = event;
}
private void initCurDate() {
Calendar instance = Calendar.getInstance();
tdYear = instance.get(Calendar.YEAR);
tdMonth = instance.get(Calendar.MONTH) + 1;
tdDay = instance.get(Calendar.DAY_OF_MONTH);
}
private int itemOfYear(int year) {
return year - START_YEAR;
}
private int itemOfMonth(int month) {
return month - 1;
}
private int itemOfDay(int day) {
return day - 1;
}
/**
* dapeter[0]->[1~28] dapeter[1]->[1~29] <br>
* dapeter[2]->[1~30] dapeter[3]->[1~31]
* @param year
* @param month
* @return
*/
private int indexAdapter(int year,int month) {
int index_data[] = {31,28,31,30,31,30,31,31,30,31,30,31};
if (month == 2) {
return DateTimeUtils.isLeapYear(year) ? 1 : 0;
} else {
if (index_data[month - 1] == 31) {
return 3;
} else {
return 2;
}
}
}
private void initAdapters() {
yearAdapter = new NumericWheelAdapter(START_YEAR,END_YEAR,"%4d");
monthAdapter = new NumericWheelAdapter(1,12,"d");
for (int i = 0; i < dayAdapter.length; i++) {
dayAdapter[i] = new NumericWheelAdapter(1,28 + i,"d");
}
sltYear = tdYear;
sltMonth = tdMonth;
sltDay = tdDay;
//赋值数据
wlvYear.setVisibleItems(3);
wlvYear.setCyclic(true);
wlvYear.setAdapter(yearAdapter);
int itemYear = itemOfYear(sltYear);
wlvYear.setCurrentItem(itemYear);
wlvMonth.setVisibleItems(3);
wlvMonth.setCyclic(true);
wlvMonth.setAdapter(monthAdapter);
int itemMonth = itemOfMonth(sltMonth);
wlvMonth.setCurrentItem(itemMonth);
int adapterIndex = indexAdapter(sltYear,sltMonth);
curDayAdapter = dayAdapter[adapterIndex];
wlvDay.setVisibleItems(3);
wlvDay.setCyclic(true);
wlvDay.setAdapter(curDayAdapter);
int itemDay = itemOfDay(sltDay);
wlvDay.setCurrentItem(itemDay);
wlvYear.addChangingListener(new OnWheelChangedListener() {
@Override
public void onChanged(WheelView wheel, int oldValue, int newValue) {
// TODO Auto-generated method stub
strSltYear = yearAdapter.getItem(newValue);
android.util.Log.i("",String.format("old=%d new=%d v=%s",
oldValue,newValue,strSltYear));
if (strSltYear != null) {
sltYear = Integer.valueOf(strSltYear);
if (sltMonth == 2) {
int tmpIndex = indexAdapter(sltYear,sltMonth);
NumericWheelAdapter tmpAdapter = dayAdapter[tmpIndex];
if (tmpAdapter != curDayAdapter) {
curDayAdapter = tmpAdapter;
wlvDay.setAdapter(curDayAdapter);
}
}
} else {
sltYear = 0;
}
}
});
wlvMonth.addChangingListener(new OnWheelChangedListener() {
@Override
public void onChanged(WheelView wheel, int oldValue, int newValue) {
// TODO Auto-generated method stub
strSltMonth = monthAdapter.getItem(newValue);
android.util.Log.i("",String.format("old=%d new=%d v=%s",
oldValue,newValue,strSltMonth));
if (strSltMonth != null) {
sltMonth = Integer.valueOf(strSltMonth);
if (sltYear != 0 && sltMonth != 0) {
int tmpIndex = indexAdapter(sltYear,sltMonth);
NumericWheelAdapter tmpAdapter = dayAdapter[tmpIndex];
if (tmpAdapter != curDayAdapter) {
curDayAdapter = tmpAdapter;
wlvDay.setAdapter(curDayAdapter);
}
}
} else {
sltMonth = 0;
}
}
});
wlvDay.addChangingListener(new OnWheelChangedListener() {
@Override
public void onChanged(WheelView wheel, int oldValue, int newValue) {
// TODO Auto-generated method stub
strSltDay = curDayAdapter.getItem(newValue);
android.util.Log.i("",String.format("old=%d new=%d v=%s",
oldValue,newValue,strSltDay));
if (strSltDay != null) {
sltDay = Integer.valueOf(strSltDay);
} else {
sltDay = 0;
}
}
});
}
private void selectDate() {
hide();
}
/**
* 回调接口
*/
public interface OnSelectDateEvent {
public void onSelectDateResult(int year,int month,int day);
};
}
android 地址 日期选择器
package com.demo.dtselector;
import com.custom.dtselector.dialog.DateSelectorDialog;
import com.custom.dtselector.dialog.DateSelectorDialog.OnSelectDateEvent;
import com.custom.dtselector.dialog.TimeSelectorDialog;
import com.custom.dtselector.dialog.TimeSelectorDialog.OnSelectTimeEvent;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class DateTimeSelectorActivity extends Activity {
private Activity activity = null;
private DateSelectorDialog dateDialog = null;
private TimeSelectorDialog timeDialog = null;
private TextView txt_date_show = null;
private TextView txt_time_show = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.datetime_main);
activity = this;
Button btnDate = (Button)findViewById(R.id.btn_date_selector);
btnDate.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
showDateDialog();
}
});
Button btnTime = (Button)findViewById(R.id.btn_time_selector);
btnTime.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
showTimeDialog();
}
});
txt_date_show = (TextView)findViewById(R.id.txt_date_show);
txt_time_show = (TextView)findViewById(R.id.txt_time_show);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.datetime_selector, menu);
return true;
}
private void showDateDialog() {
if (dateDialog == null) {
dateDialog = new DateSelectorDialog();
dateDialog.init(activity);
dateDialog.setOnSelectDateEvent(new OnSelectDateEvent(){
@Override
public void onSelectDateResult(int year, int month, int day) {
// TODO Auto-generated method stub
txt_date_show.setText(String.format("d-d-d",
year,month,day));
}
});
}
dateDialog.show();
}
private void showTimeDialog() {
if (timeDialog == null) {
timeDialog = new TimeSelectorDialog();
timeDialog.init(activity);
timeDialog.setOnSelectTimeEvent(new OnSelectTimeEvent(){
@Override
public void onSelectTimeResult(int hour, int minute, int second) {
// TODO Auto-generated method stub
txt_time_show.setText(String.format("d:d:d",
hour,minute,second));
}
});
} else {
timeDialog.update(null);
}
timeDialog.show();
}
}
Java NIO 聊天室 JSwing
package com.ui.server;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ServerBootFrame extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
JPanel jp = new JPanel(new BorderLayout());
JPanel jp1 = new JPanel(new FlowLayout());
JScrollPane jsp1 = new JScrollPane();
JButton jbStart = new JButton("启动");
JButton jbEnd = new JButton("关闭");
JTextArea jtaState = new JTextArea(10, 25);
Font font = new Font("Serif", Font.BOLD, 18);
Color fore = Color.YELLOW;
Color back = new Color(81, 217, 251);
public ServerBootFrame(String title) {
super(title);
this.getContentPane().add(jp);
jp.add(jsp1, "Center");
jsp1.getViewport().add(jtaState);
jp.add(jp1, "South");
jp1.add(jbStart);
jp1.add(jbEnd);
jtaState.setFont(font);
jtaState.setForeground(fore);
jtaState.setBackground(back);
jp1.setBackground(back);
this.setResizable(false);
this.setLocation(250, 250);
}
public void showFrame() {
this.pack();
this.setVisible(true);
}
public void bootingServer(final BootEndInterface bt) {
this.jbStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bt.boot();
}
});
}
public void endingServer(final BootEndInterface ed) {
this.jbEnd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ed.end();
}
});
}
public void closeWindow(final BootEndInterface ed) {
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e1) {
ed.end();
}
});
}
public void appendStringTojtaState(String str) {
jtaState.append(str);
}
}
package com.ui.client;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.sql.*;
public class LoginFrame extends JFrame
{
JLabel jUserName=new JLabel("用户姓名:");
JLabel jUserPsd=new JLabel("用户密码:");
JTextField txtUserName=new JTextField("",10);
JPasswordField txtUserPsd=new JPasswordField(10);
JButton okButton=new JButton("确定");
JButton regButton=new JButton("注册");
JPanel jp=new JPanel(new GridLayout(2,1));
JPanel jp1=new JPanel(new FlowLayout(FlowLayout.CENTER));
JPanel jp2=new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel jp3=new JPanel(new FlowLayout());
Font f=new Font("Serif",Font.BOLD,15);
public LoginFrame()
{
super("用户登陆界面");
this.setLocation(250,250);
this.getContentPane().add(jp,"Center");
this.getContentPane().add(jp3,"South");
jp.add(jp1);jp.add(jp2);
jp1.add(jUserName);jp1.add(txtUserName);
jp2.add(jUserPsd);jp2.add(txtUserPsd);
jp3.add(okButton);jp3.add(regButton);
txtUserName.setFont(f);
txtUserPsd.setFont(f);
txtUserPsd.setEchoChar('x');
txtUserName.setToolTipText("请输入用户名");
txtUserPsd.setToolTipText("请输入用户密码");
okButton.addActionListener(new SolveButtonEvent(1));
regButton.addActionListener(new SolveButtonEvent(2));
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void showWindow()
{
this.pack();
this.setVisible(true);
}
public void closeWindow()
{
this.dispose();
}
public String getUserName()
{
return this.txtUserName.getText().trim();
}
public String getUserPassword()
{
return new String(this.txtUserPsd.getPassword());
}
class SolveButtonEvent implements ActionListener
{
int select=0;
public SolveButtonEvent(int select)
{
this.select=select;
}
public void actionPerformed(ActionEvent e)
{
//int x=(int) LoginFrame.this.txtUserName.getLocationOnScreen().getX();
//int y=(int) LoginFrame.this.txtUserName.getLocationOnScreen().getY();
String userName=LoginFrame.this.getUserName();
String userPsd=LoginFrame.this.getUserPassword();
int nameLength=userName.length();
int psdLength=userPsd.length();
if(select==1)
{ if(nameLength>0 && psdLength>0 )
{
if(LoginFrame.this.query(userName,userPsd)==true)
{
LoginFrame.this.closeWindow();
//new Client();
}
else
{
MyDialog md=new MyDialog(LoginFrame.this,"提示窗口","错误!","用户名或密码错误.\n登陆失败");
md.showDialog();
}
}
else
{
if(nameLength==0)
{
MyDialog md=new MyDialog(LoginFrame.this,"提示窗口","提示","用户名不能为空");
md.showDialog();
}
else if(psdLength==0)
{
MyDialog md=new MyDialog(LoginFrame.this,"提示窗口","提示","用户密码不能为空");
md.showDialog();
}
}
}
else if(select==2)
{
RegisterFrame rf=new RegisterFrame(LoginFrame.this);
rf.showWindow();
}
}
}
public boolean query(String userName,String userPsd)
{
Connection conn=null;
PreparedStatement psm=null;
ResultSet rs=null;
String sql="select * from user_manager where name=? and psd=?";
boolean result=false;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xdf","scott","tiger");
psm=conn.prepareStatement(sql);
psm.setString(1,userName);
psm.setString(2,userPsd);
rs=psm.executeQuery();
//rs结果集指向第一条记录的前一个位置
//如果第一条记录为空表示用户名或密码错误
if(rs.next()==true)
{
result=true;
this.closeWindow();
}
psm.close();
conn.close();
}
catch(ClassNotFoundException e1){ e1.printStackTrace(); }
catch(SQLException e2){ e2.printStackTrace(); }
catch(Exception e3){ e3.printStackTrace(); }
return result;
}
}
package com.nio.client;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import com.nio.user.ClientUser;
import com.nio.user.ClientUserManager;
import com.nio.user.UserData;
public class NIOClient {
private ClientUserManager cltManager = null;
//通道管理器
private Selector selector;
/**
* 获得一个Socket通道,并对该通道做一些初始化的工作
* @param ip 连接的服务器的ip
* @param port 连接的服务器的端口号
* @throws IOException
*/
public void initClient(String ip,int port) throws IOException {
cltManager = ClientUserManager.instance();
// 获得一个Socket通道
SocketChannel channel = SocketChannel.open();
// 设置通道为非阻塞
channel.configureBlocking(false);
// 获得一个通道管理器
this.selector = Selector.open();
// 客户端连接服务器,其实方法执行并没有实现连接,需要在listen()方法中调
//用channel.finishConnect();才能完成连接
channel.connect(new InetSocketAddress(ip,port));
//将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_CONNECT事件。
channel.register(selector, SelectionKey.OP_CONNECT);
}
/**
* 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理
* @throws IOException
* @throws InterruptedException
*/
@SuppressWarnings("unchecked")
public void listen() throws IOException, InterruptedException {
// 轮询访问selector
while (true) {
// 选择一组可以进行I/O操作的事件,放在selector中,客户端的该方法不会阻塞,
//这里和服务端的方法不一样,查看api注释可以知道,当至少一个通道被选中时,
//selector的wakeup方法被调用,方法返回,而对于客户端来说,通道一直是被选中的
selector.select();
// 获得selector中选中的项的迭代器
Iterator ite = this.selector.selectedKeys().iterator();
while (ite.hasNext()) {
SelectionKey key = (SelectionKey) ite.next();
// 连接事件发生
if (key.isConnectable()) {
SocketChannel channel = (SocketChannel) key
.channel();
System.out.println("channel client ?" + channel);
// 如果正在连接,则完成连接
if(channel.isConnectionPending()){
channel.finishConnect();
}
//设置成非阻塞
channel.configureBlocking(false);
//在这里可以给服务端发送信息哦
//channel.write(ByteBuffer.wrap(new String("向服务端发送了一条信息").getBytes()));
//在和服务端连接成功之后,为了可以接收到服务端的信息,需要给通道设置读的权限。
channel.register(this.selector, SelectionKey.OP_READ);
//添加用户
UserData userData = new UserData();
userData.lineState = 1;
userData.channel = channel;
cltManager.addUser(userData);
//连接成功发送一个通知消息
UIClient.sendUserInfoMsg();
} else if (key.isReadable()) {
ClientUser cltUser = cltManager.getUser((SocketChannel)key.channel());
if (!cltUser.read()) {
key.channel().close();
}
}
//删除已选的key,以防重复处理
ite.remove();
}
}
}
}
package com.nio.server;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
import com.nio.user.ServerUser;
import com.nio.user.ServerUserManager;
import com.nio.user.UserData;
import com.ui.server.BootEndInterface;
import com.ui.server.ServerBootFrame;
public class NIOServer implements BootEndInterface {
private ServerBootFrame serverFrame = new ServerBootFrame("服务器端");
private ServerUserManager userManager = null;
HashMap<String, String> hmClient = new HashMap<String, String>();
Vector<String> client = new Vector<String>();
int count = 0;
private static NIOServer nioServer = null;
public NIOServer() {
serverFrame.showFrame();
serverFrame.bootingServer(this);
serverFrame.endingServer(this);
serverFrame.closeWindow(this);
nioServer = this;
}
// 通道管理器
private Selector selector;
/**
* 获得一个ServerSocket通道,并对该通道做一些初始化的工作
*
* @param port
* 绑定的端口号
* @throws IOException
*/
public void initServer(int port) throws IOException {
serverFrame.appendStringTojtaState("服务器(NIO机制)启动中......\n");
// 获得一个ServerSocket通道
ServerSocketChannel serverChannel = ServerSocketChannel.open();
// 设置通道为非阻塞
serverChannel.configureBlocking(false);
// 将该通道对应的ServerSocket绑定到port端口
serverChannel.socket().bind(new InetSocketAddress(port));
// 获得一个通道管理器
this.selector = Selector.open();
// 将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_ACCEPT事件,注册该事件后,
// 当该事件到达时,selector.select()会返回,如果该事件没到达selector.select()会一直阻塞。
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
//System.out.println("serverChannel 0?" + serverChannel);
}
/**
* 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理
*
* @throws IOException
*/
@SuppressWarnings("unchecked")
public void listen() throws IOException {
// System.out.println("服务端启动成功!");
serverFrame.appendStringTojtaState("服务器(NIO机制)启动成功......\n");
// 轮询访问selector
while (true) {
// 当注册的事件到达时,方法返回;否则,该方法会一直阻塞
selector.select();
// 获得selector中选中的项的迭代器,选中的项为注册的事件
Iterator<?> ite = this.selector.selectedKeys().iterator();
while (ite.hasNext()) {
SelectionKey key = (SelectionKey) ite.next();
// 客户端请求连接事件
if (key.isAcceptable()) {
ServerSocketChannel server = (ServerSocketChannel) key
.channel();
// 获得和客户端连接的通道
SocketChannel channel = server.accept();
System.out.println("channel A?" + channel);
// 设置成非阻塞
channel.configureBlocking(false);
// 在这里可以给客户端发送信息哦
// channel.write(ByteBuffer.wrap(new
// String("向客户端发送了一条信息").getBytes()));
// 在和客户端连接成功之后,为了可以接收到客户端的信息,需要给通道设置读的权限。
channel.register(this.selector, SelectionKey.OP_READ);
// 添加一个玩家对象
UserData userData = new UserData();
userData.lineState = 1;
userData.channel = channel;
userManager.addUser(userData);
} else if (key.isReadable()) {
ServerUser serverUser = userManager
.getUser((SocketChannel) key.channel());
// 读取数据失败
if (!serverUser.read()) {
serverUser.clean();
key.channel().close();
}
}
// 删除已选的key,以防重复处理
ite.remove();
}
}
}
/**
* 启动服务端测试
*
* @throws IOException
*/
public static void main(String[] args) throws IOException {
new NIOServer();
}
@Override
public void boot() {
userManager = ServerUserManager.instance();
userManager.initUsers();
serverFrame.appendStringTojtaState("创建玩家内存数据对象成功...\n");
new Thread(new Runnable() {
@Override
public void run() {
try {
NIOServer.this.initServer(5555);
NIOServer.this.listen();
} catch (Exception e) {
serverFrame.appendStringTojtaState("服务器启动失败......\n");
}
}
}).start();
//服务端主逻辑处理
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
Thread.sleep(1);
userManager.run();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
@Override
public void end() {
if (selector != null) {
try {
selector.close();
selector = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.exit(0);
}
public void solveMsg(String message) {
try {
System.out.println(message);
// 对消息进行分析
String msg[] = message.split("#");
if (msg[0].equals("AddUser") == true) {
hmClient.put(msg[1], msg[2]);
sendUsersToOneUser(msg[1]);
if (likeThisName(msg[1]))// 如果出现同名用户,则在用户名后面添加数字来区分
{
msg[1] = msg[1] + count;
}
client.add(msg[1]);
serverFrame.appendStringTojtaState(msg[1] + "上线...\n");
sendMessageToAllUsers(
"AddUser" + "#" + msg[1] + "#" + hmClient.get(msg[1]),
msg[1]);
} else if (msg[0].equals("UserQuit") == true) {
sendMessageToAllUsers("UserQuit" + "#" + msg[1] + "#"
+ hmClient.get(msg[1]), msg[1]);
serverFrame.appendStringTojtaState(msg[1] + "离线...\n");
deleteKeyValue(msg[1]);
client.remove(msg[1]);
// 应该删除vecUser容器中的对应的Socket对象
} else if (msg[0].equals("Message") == true) { // 如果将消息发送给特定用户
if (msg[1].equals("One") == true) {
sendMessageToOneUser("Message" + "#" + msg[2] + "#"
+ msg[6], msg[4]);
} else// 将消息发送给全部用户
{
sendMessageToAllUsers("Message" + "#" + msg[2] + "#"
+ msg[4], msg[2]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMessageToAllUsers(String msg, String notSendToThisUserName) throws UnsupportedEncodingException {
ServerUser lstUsers[] = userManager.getUsers();
for (int i = 0; i < lstUsers.length; i++) {
if (lstUsers[i].channel != null) {
String address = lockOut(""
+ lstUsers[i].channel.socket().getRemoteSocketAddress());
if ( !address.equals(hmClient.get(notSendToThisUserName)) ) {
lstUsers[i].write(msg.getBytes("utf-8"));
}
}
}
}
public void sendMessageToOneUser(String msg, String sendToThisUserName) throws UnsupportedEncodingException {
ServerUser lstUsers[] = userManager.getUsers();
for (int i = 0; i < lstUsers.length; i++) {
if (lstUsers[i].channel != null) {
String address = lockOut(""
+ lstUsers[i].channel.socket().getRemoteSocketAddress());
if ( address.equals(hmClient.get(sendToThisUserName)) ) {
lstUsers[i].write(msg.getBytes("utf-8"));
break;
}
}
}
}
// 方法完成将在线用户添给用户的下拉表中
public void sendUsersToOneUser(String newUserName) throws UnsupportedEncodingException {
Iterator<String> it = client.listIterator();
for (; it.hasNext();) {
String name = it.next();
String ipAndPort = hmClient.get(name);
sendMessageToOneUser("OnlyAddUser" + "#" + name + "#" + ipAndPort,
newUserName);
}
}
// 将键值对添加到hmClient哈希表中
public void createKeyValue(String userName, String socketAddress) {
hmClient.put(userName, socketAddress);
}
// 从哈希表中删除指定键值对(键为:userName);
public void deleteKeyValue(String userName) {
hmClient.remove(userName);
}
// 将字符串前面的斜杠去掉
public String lockOut(String socketAddress) {
return socketAddress.substring(1, socketAddress.length());
}
// 如果client容器中存放的用户名出现相似用户,则用户名后面添加一个数字
public boolean likeThisName(String thisName) {
count = 0;
for (Iterator it = client.listIterator(); it.hasNext();) {
String temp = (String) it.next();
if (temp.startsWith(thisName) == true) {
count++;
}
}
if (count > 0)
return true;
else
return false;
}
public static void handleMessage(String msg) {
// System.out.println("服务端收到信息:" + msg);
nioServer.solveMsg(msg);
}
}
android 百度地图 定位示例
1.需要在 http://developer.baidu.com/ 注册开发者(个人或公司)账号
2.需要申请Key
打开网址 http://developer.baidu.com/map/index.php
点击 创建应用,跟流程创建应用app
3.点击相关下载->一键下载
4.调用百度地图的APP 需要在 AndroidManifest.xml 添加
<application
android:name="baidumapsdk.demo.DemoApplication"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
这里需要添加key,创建应用后,会有这个key
<meta-data
android:name="com.baidu.lbsapi.API_KEY"
android:value="6t2yuIFylnRG7ECj1xHYuelY" />
.....
package com.obtk.mapdemo;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMapOptions;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.app.Activity;
import com.obtk.mapdemo.R;
public class MapApiDemoActivity extends Activity implements
OnGetGeoCoderResultListener {
private MapView mMapView = null;
private BaiduMap mBaiduMap = null;
private GeoCoder mSearch = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// SDK初始化
SDKInitializer.initialize(getApplicationContext());
//当前视图
setContentView(R.layout.activity_map_api_demo);
//创建地图对象
init();
final Button btn_location = (Button) findViewById(R.id.btn_location);
btn_location.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
getLocation();
btn_location.setEnabled(false);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_map_api_demo, menu);
return true;
}
/**
* 初始化方法
*/
private void init() {
//mMapView = (MapView) findViewById(R.id.bmapview);
mMapView = new MapView(this, new BaiduMapOptions());
mBaiduMap = mMapView.getMap();
/**添加一个对象*/
RelativeLayout rlly_map = (RelativeLayout)findViewById(R.id.rlly_map);
rlly_map.addView(mMapView);
// 开启定位图层
mBaiduMap.setMyLocationEnabled(true);
//初始化搜索模块,注册事件监听
mSearch = GeoCoder.newInstance();
mSearch.setOnGetGeoCodeResultListener(this);
}
@Override
protected void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
protected void onDestroy() {
// 退出时销毁定位
mLocClient.stop();
// 关闭定位图层
mBaiduMap.setMyLocationEnabled(false);
mMapView.onDestroy();
mMapView = null;
super.onDestroy();
}
// 定位相关
LocationClient mLocClient;
public MyLocationListenner myListener = new MyLocationListenner();
private LocationMode mCurrentMode;
private boolean isFirstLoc = true;
/**
* 定位SDK监听函数
*/
public class MyLocationListenner implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
// map view 销毁后不在处理新接收的位置
if (location == null || mMapView == null)
return;
MyLocationData locData = new MyLocationData.Builder()
.accuracy(location.getRadius())
//此处设置开发者获取到的方向信息,顺时针0-360
.direction(100).latitude(location.getLatitude())
.longitude(location.getLongitude()).build();
mBaiduMap.setMyLocationData(locData);
if (isFirstLoc) {
isFirstLoc = false;
LatLng ll = new LatLng(location.getLatitude(),
location.getLongitude());
MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
mBaiduMap.animateMapStatus(u);
}
String addr = location.getAddrStr();
if (addr != null) {
Log.i("Test", addr);
} else {
Log.i("Test","error");
}
double longitude = location.getLongitude();
double latitude = location.getLatitude();
if (longitude > 0 && latitude > 0) {
Log.i("Test",String.format("纬度:%f 经度:%f", latitude,longitude));
LatLng ptCenter = new LatLng(latitude,longitude);
// 反Geo搜索
mSearch.reverseGeoCode(new ReverseGeoCodeOption()
.location(ptCenter));
}
//停止定位
mLocClient.stop();
}
public void onReceivePoi(BDLocation poiLocation) {
}
}
private void getLocation() {
// 定位初始化
mLocClient = new LocationClient(this);
mLocClient.registerLocationListener(myListener);
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true);//打开gps
option.setCoorType("bd09ll"); //设置坐标类型
option.setScanSpan(5000); //定位时间间隔
mLocClient.setLocOption(option);
mLocClient.start();
}
@Override
public void onGetGeoCodeResult(GeoCodeResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
// TODO Auto-generated method stub
if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(MapApiDemoActivity.this, "抱歉,未能找到结果", Toast.LENGTH_LONG)
.show();
return;
}
mBaiduMap.clear();
// mBaiduMap.addOverlay(new MarkerOptions().position(result.getLocation())
// .icon(BitmapDescriptorFactory
// .fromResource(R.drawable.icon_marka)));
mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result
.getLocation()));
Toast.makeText(MapApiDemoActivity.this, result.getAddress(),
Toast.LENGTH_LONG).show();
String province = result.getAddressDetail().province;
String city = result.getAddressDetail().city;
if (province != null && city != null) {
}
}
}
QRCodeTools.zip
1.可编解码二维码
2.二维码中间可嵌入logo
3.实现了win10环境下的批处理文件
4.可参考源码工程修改工具,实现更多的功能
Android计算器程序
支持多重小括号运算,
支持严格数学计算,
自适应分辨率