java+Socket实现客户端服务器端的登录通信
服务器和客户端都是自己再网上copy的代码,有一个bug就是当客户端退出的时候会报错,这个bug很容易解决。先来看看我们的服务器端代码:(服务器端用了数据库的查询登陆) package Test;
import java.io.IOException;
import java.net.InetSocketAddress; import java.net.ServerSocket; import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel; import java.sql.ResultSet;
import java.sql.SQLException; import java.util.Iterator;
import java.util.Set;
public class Server {
public static final int serverport =5555;
public static final String isack="ack";
public static final String isnak="nak";
private ByteBuffer echobuffer=ByteBuffer.allocate(1024);
public Server() {
}
public static void main(String[] args) {
new Server().buildserver();
}
public void buildserver(){
try {
ServerSocketChannel ssc=ServerSocketChannel.open();
ssc.configureBlocking(false);
ServerSocket ss=ssc.socket();
ss.bind(new
InetSocketAddress("127.0.0.1",serverport));
Selector selector=Selector.open();
SelectionKey
skey=ssc.register(selector,SelectionKey.OP_ACCEPT);
while(true)
{
int num=selector.select();
if(num<1)
{
continue;
}
Set selectedKeys=selector.selectedKeys();
Iterator it=selectedKeys.iterator();
while(it.hasNext())
{
SelectionKey key=(SelectionKey) it.next();
if((key.readyOps()&SelectionKey.OP_ACCEPT)==SelectionKey.OP_ACCEPT)
{
ServerSocketChannel
serverchannel=(ServerSocketChannel) key.channel();
SocketChannel
sc=serverchannel.accept();
sc.configureBlocking(false);
SelectionKey
newKey=sc.register(selector,SelectionKey.OP_READ);
it.remove();
System.out.print("get connection from"+sc);
}
else{
if((key.readyOps()&SelectionKey.OP_READ)==SelectionKey.OP_READ)
{
SocketChannel sc=(SocketChannel)
key.channel();
int bytesEchoed=0;
while((bytesEchoed=sc.read(echobuffer))>0)
{
System.out.println("bytesEchoed"+bytesEchoed);
}
echobuffer.flip();
System.out.println("limet
"+echobuffer.limit());
byte [] content =new byte[echobuffer.limit()];
echobuffer.get(content);
String result=new String(content);
doPost(result,sc);
echobuffer.clear();
it.remove();
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doPost(String str, SocketChannel sc) {
boolean isok=false;
int index=str.indexOf('|');
if(index>0)
{
String name=str.substring(0,index);
String pswd=str.substring(index+1);
String sql="select name,password from login where
name='"+name+"'and password='"+pswd+"'";
SqlConn sc1=new SqlConn();
ResultSet rs=sc1.getResult(sql);
boolean f=false;
try {
f=rs.first();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(pswd==null)
{
pswd="";
}if(name!=null)
{
if(f)
{
isok=true;
}
else{
isok=false;
}
String result="";
if(isok)
{
result="ack";
}
else{
result="nak";
}
ByteBuffer bb=ByteBuffer.allocate(result.length());
bb.put(result.getBytes());
bb.flip();
try {
sc.write(bb);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bb.clear();
}
}
}
}
下面是客户端:
package Test;
import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField;
public class client extends JFrame{
private JLabel jLabel1;
private JTextField usertext;
private JLabel jLabel2;
private JButton loginbutton;
private JLabel hint;
private JTextField passtext;
String name;
String password;
public client() {
{
getContentPane().setLayout(null);
}
{
jLabel1 = new JLabel();
getContentPane().add(jLabel1);
jLabel1.setText("\u7528\u6237\u540d");
jLabel1.setBounds(39, 39, 63, 18);
}
{
usertext = new JTextField();
getContentPane().add(usertext);
usertext.setBounds(109, 37, 156, 22);
}
{
jLabel2 = new JLabel();
getContentPane().add(jLabel2);
jLabel2.setText("\u5bc6\u7801");
jLabel2.setBounds(39, 77, 38, 18);
}
{
passtext = new JTextField();
getContentPane().add(passtext);
passtext.setBounds(109, 75, 156, 22);
}
{
loginbutton = new JButton();
getContentPane().add(loginbutton);
loginbutton.setText("\u767b\u9646");
loginbutton.setBounds(90, 113, 91, 28);
loginbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
name=usertext.getText().trim();
password=passtext.getText().trim();
if(password.equals(""))
{
password="";
}
if(name!=null&&name.length()>0)
{
hint.setText("正在验证客户端,请稍后......");
start();
}
}
public void start() {
new Thread(new Runnable(){
public void run() {
try {
Socket s=new Socket("localhost",5555);
OutputStream os;
InputStream is;
os=s.getOutputStream();
os.write(name.getBytes());
os.write('|');
os.write(password.getBytes());
os.flush();
Thread.sleep(1000);
is=s.getInputStream();
int len=is.available();
System.out.println("length: "+len);
byte[] bytes=new byte[len];
is.read(bytes);
String result=new String(bytes);
System.out.println("result: "+result);
if(result.equals("ack"))
{
hint.setText("验证成功,欢迎光临");
}else{
passtext.setText(null);
hint.setText("用户名或密码有误,请重新
输入");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
});
}
{
hint = new JLabel();
getContentPane().add(hint);
hint.setBounds(90, 8, 172, 23);
}
{
this.setSize(318, 188);
setVisible(true);
}
}
public static void main(String[] args) {
new client();
}
}
下面是数据库的链接:
package Test;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class SqlConn
{
String driverName =
"com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL = "jdbc:sqlserver://localhost:1433;
DatabaseName=project";
String userName = "sa";
String userPwd = "123";
Connection con;
ResultSet rs;
Statement stmt;
public SqlConn()
{
try{
Class.forName(driverName);
con=DriverManager.getConnection(dbURL, userName,
userPwd);
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
}
catch ( ClassNotFoundException cnfex ) {
System.err.println("Failed To Connect DataBase." );
cnfex.printStackTrace();
System.exit( 1 ); // terminate program
}
catch(SQLException sqle)
{
System.out.println(sqle.toString());
}
}
public ResultSet getResult(String sql)
{
try{
rs=stmt.executeQuery(sql);
return rs;
}
catch(SQLException sqle)
{
System.out.println(sqle.toString());
return null;
}
}
public boolean updateSql(String strSQL)
{
try{
stmt.executeUpdate(strSQL);
con.commit();
return true;
}
catch(SQLException sqle)
{
System.out.println(sqle.toString());
return false;
}
}
public void closeConnection()
{
try
{
con.close();
}
catch(SQLException sqle)
{
System.out.println(sqle.toString());
}
}
}
本文档为【java+Socket实现客户端服务器端的登录通信】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑,
图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。