文件名称:Java NIO 聊天室
文件大小:171KB
文件格式:RAR
更新时间:2018-09-26 06:27:18
Java NIO 聊天室
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
【文件预览】:
NIOChat
----bin()
--------com()
----tools()
--------client.jar(53KB)
--------server.jar(53KB)
----.settings()
--------org.eclipse.jdt.core.prefs(598B)
----src()
--------com()
----.project(383B)
----.classpath(301B)