web版仿微信聊天分界面,在线聊天项目一

事先做过1版h5微信聊天移动端,那段日子闲来无事就照管了下在此之前项目,又再一次在原本的那版基础回升级了下,如是就有了未来的h五仿微信聊天高仿版,新添了微聊、通信录、研究、笔者多少个模块
左右触摸滑屏切换,聊天页面优化了多图预览、摄像播放,长按菜单UI,聊天尾部编辑器重新优化整治(新增增加表情),弹窗则用到了谐和开采的wcPop.js,具体看档案的次序效益图吧!

后日开荒了壹款手提式无线电话机端h五仿微信聊天,人仅仅不停学习才具开荒进取,这段时光倒腾着整理了下在此以前项目,又重新在本来的那版基础上支出了一款仿微信聊天计算机端web版本,聊天页面又重新优化了多图预览、摄像播放,右键菜单menu,聊天底部编辑器模块重新优化源码,弹窗则是承接选拔在此之前自身支付的wcPop.js,具体看档案的次序效益图吧!

在线聊天项目布局图:

在线聊天项目结构图:

html代码片段:

效果图:

亚洲必赢官网 1

亚洲必赢官网 2

<!-- //微聊底部功能面板 -->
<div class="wc__footTool-panel">
    <!-- 输入框模块 -->
    <div class="wc__editor-panel wc__borT flexbox">
        <div class="wrap-editor flex1"><div class="editor J__wcEditor" contenteditable="true"></div></div>
        <i class="btn btn-emotion"></i>
        <i class="btn btn-choose"></i>
        <button class="btn-submit J__wchatSubmit">发送</button>
    </div>

    <!-- 表情、选择模块 -->
    <div class="wc__choose-panel wc__borT" style="display: none;">
        <!-- 表情区域 -->
        <div class="wrap-emotion" style="display: none;">
            <div class="emotion__cells flexbox flex__direction-column">
                <div class="emotion__cells-swiper flex1" id="J__swiperEmotion">
                    <div class="swiper-container">
                        <div class="swiper-wrapper"></div>
                        <div class="pagination-emotion"></div>
                    </div>
                </div>
                <div class="emotion__cells-footer" id="J__emotionFootTab">
                    <ul class="clearfix">
                        <li class="swiperTmpl cur" tmpl="swiper__tmpl-emotion01"><img src="img/emotion/face01/face-lbl.png" alt="亚洲必赢官网 3"></li>
                        <li class="swiperTmpl" tmpl="swiper__tmpl-emotion02"><img src="img/emotion/face02/face-lbl.gif" alt="亚洲必赢官网 4"></li>
                        <li class="swiperTmpl" tmpl="swiper__tmpl-emotion03"><img src="img/emotion/face03/face-lbl.gif" alt="亚洲必赢官网 5"></li>
                        <li class="swiperTmpl" tmpl="swiper__tmpl-emotion04"><img src="img/emotion/face04/face-lbl.gif" alt="亚洲必赢官网 6"></li>
                        <li class="swiperTmpl" tmpl="swiper__tmpl-emotion05"><img src="img/emotion/face05/face-lbl.gif" alt="亚洲必赢官网 7"></li>
                        <li class="swiperTmpl" tmpl="swiper__tmpl-emotion06"><img src="img/emotion/face06/face-lbl.gif" alt="亚洲必赢官网 8"></li>
                        <li class="swiperTmplSet"><img src="img/wchat/icon__emotion-set.png" alt="亚洲必赢官网 9"></li>
                    </ul>
                </div>
            </div>
        </div>
        <!-- 选择区域 -->
        <div class="wrap-choose" style="display: none;">
            <div class="choose__cells">
                <ul class="clearfix">
                    <li><a class="J__wchatZp" href="javascript:;"><img src="img/wchat/icon__choose-zp.png" /><input type="file" accept="image/*" /><em>照片</em></a></li>
                    <li><a class="J__wchatSp" href="javascript:;"><img src="img/wchat/icon__choose-sp.png" /><input type="file" accept="video/*" /><em>视频</em></a></li>
                    <li><a class="J__wchatHb" href="javascript:;"><img src="img/wchat/icon__choose-hb.png" /><em>红包</em></a></li>
                    <li><a class="J__wchatSc" href="javascript:;"><img src="img/wchat/icon__choose-sc.png" /><em>我的收藏</em></a></li>
                    <li><a class="J__wchatWj" href="javascript:;"><img src="img/wchat/icon__choose-wj.png" /><em>文件</em></a></li>
                </ul>
            </div>
        </div>
    </div>
</div>

<div class="wc__choosePanel-tmpl">
    <!-- //红包模板.begin -->
    <div id="J__popupTmpl-Hongbao" style="display:none;">
        <div class="wc__popupTmpl tmpl-hongbao">
            <i class="wc-xclose"></i>
            <ul class="clearfix">
                <li class="item flexbox">
                    <label class="txt">总金额</label><input class="ipt-txt flex1" type="tel" name="hbAmount" placeholder="0.00" /><em class="unit">元</em>
                </li>
                <li class="item flexbox">
                    <label class="txt">红包个数</label><input class="ipt-txt flex1" type="tel" name="hbNum" placeholder="填写个数" /><em class="unit">个</em>
                </li>
                <li class="tips">在线人数共<em class="memNum">186</em>人</li>
                <li class="item item-area">
                    <textarea class="describe" name="content" placeholder="恭喜发财,大吉大利"></textarea>
                </li>
                <li class="amountTotal">¥<em class="num">0.00</em></li>
            </ul>
        </div>
    </div>
    <!-- //红包模板.end -->
</div>

亚洲必赢官网 10

多用户登录效果图:

多用户登入效果图:

Js代码片段:

亚洲必赢官网 11

亚洲必赢官网 12

亚洲必赢官网 13

// ...长按弹出菜单
$("#J__chatMsgList").on("longTap", "li .msg", function(e){
    var that = $(this), menuTpl, menuNode = $("<div class='wc__chatTapMenu animated anim-fadeIn'></div>");
    that.addClass("taped");
    that.parents("li").siblings().find(".msg").removeClass("taped");
    var isRevoke = that.parents("li").hasClass("me");
    var _revoke = isRevoke ? "<a href='#'><i class='ico i4'></i>撤回</a>" : "";

    if(that.hasClass("picture")){
        console.log("图片长按");
        menuTpl = "<div class='menu menu-picture'><a href='#'><i class='ico i1'></i>复制</a><a href='#'><i class='ico i2'></i>收藏</a><a href='#'><i class='ico i3'></i>另存为</a>"+ _revoke +"<a href='#'><i class='ico i5'></i>删除</a></div>";
    }else if(that.hasClass("video")){
        console.log("视频长按");
        menuTpl = "<div class='menu menu-video'><a href='#'><i class='ico i3'></i>另存为</a>" + _revoke +"<a href='#'><i class='ico i5'></i>删除</a></div>";
    }else{
        console.log("文字长按");
        menuTpl = "<div class='menu menu-text'><a href='#'><i class='ico i1'></i>复制</a><a href='#'><i class='ico i2'></i>收藏</a>" + _revoke +"<a href='#'><i class='ico i5'></i>删除</a></div>";
    }

    if(!$(".wc__chatTapMenu").length){
        $(".wc__chatMsg-panel").append(menuNode.html(menuTpl));
        autoPos();
    }else{
        $(".wc__chatTapMenu").hide().html(menuTpl).fadeIn(250);
        autoPos();
    }

    function autoPos(){
        console.log(that.position().top)
        var _other = that.parents("li").hasClass("others");
        $(".wc__chatTapMenu").css({
            position: "absolute",
            left: that.position().left + parseInt(that.css("marginLeft")) + (_other ? 0 : that.outerWidth() - $(".wc__chatTapMenu").outerWidth()),
            top: that.position().top - $(".wc__chatTapMenu").outerHeight() - 8
        });
    }
});

亚洲必赢官网 14

多用户聊天效果图:

多用户聊天效果图:

效果图:

亚洲必赢官网 15

亚洲必赢官网 16

亚洲必赢官网 17

亚洲必赢官网 18

亚洲必赢官网 19

数据库效果图:

数据库效果图:

亚洲必赢官网 20

亚洲必赢官网 21

亚洲必赢官网 22

亚洲必赢官网 23

亚洲必赢官网 24

亚洲必赢官网 25



亚洲必赢官网 26

亚洲必赢官网 27

再度构建了Server类,使用了Gson方法,通过解析Json字符串,扩充Info类,简化判定进度。

web版仿微信聊天分界面,在线聊天项目一。重新创设了Server类,使用了Gson方法,通过解析Json字符串,增加Info类,简化判别进度。

亚洲必赢官网 28

// ...表情、选择区切换
$(".wc__editor-panel").on("click", ".btn", function(){
    var that = $(this);
    $(".wc__choose-panel").show();
    if (that.hasClass("btn-emotion")) {
        $(".wc__choose-panel .wrap-emotion").show();
        $(".wc__choose-panel .wrap-choose").hide();
        // 初始化swiper表情
        !emotionSwiper && $("#J__emotionFootTab ul li.cur").trigger("click");
    } else if (that.hasClass("btn-choose")) {
        $(".wc__choose-panel .wrap-emotion").hide();
        $(".wc__choose-panel .wrap-choose").show();
    }
    wchat_ToBottom();
});

// ...处理编辑器信息
var $editor = $(".J__wcEditor"), _editor = $editor[0];
function surrounds(){
    setTimeout(function () { //chrome
        var sel = window.getSelection();
        var anchorNode = sel.anchorNode;
        if (!anchorNode) return;
        if (sel.anchorNode === _editor ||
            (sel.anchorNode.nodeType === 3 && sel.anchorNode.parentNode === _editor)) {

            var range = sel.getRangeAt(0);
            var p = document.createElement("p");
            range.surroundContents(p);
            range.selectNodeContents(p);
            range.insertNode(document.createElement("br")); //chrome
            sel.collapse(p, 0);

            (function clearBr() {
                var elems = [].slice.call(_editor.children);
                for (var i = 0, len = elems.length; i < len; i++) {
                    var el = elems[i];
                    if (el.tagName.toLowerCase() == "br") {
                        _editor.removeChild(el);
                    }
                }
                elems.length = 0;
            })();
        }
    }, 10);
}
// 格式化编辑器包含标签
_editor.addEventListener("click", function () {
    //$(".wc__choose-panel").hide();
}, true);
_editor.addEventListener("focus", function(){
    surrounds();
}, true);
_editor.addEventListener("input", function(){
    surrounds();
}, false);
// 点击表情
$("#J__swiperEmotion").on("click", ".face-list span img", function(){
    var that = $(this), range;

    if(that.hasClass("face")){ //小表情
        var img = that[0].cloneNode(true);
        _editor.focus();
        _editor.blur(); //输入表情时禁止输入法

        setTimeout(function(){
            if(document.selection && document.selection.createRange){
                document.selection.createRange().pasteHTML(img);
            }else if(window.getSelection && window.getSelection().getRangeAt){
                range = window.getSelection().getRangeAt(0);
                range.insertNode(img);
                range.collapse(false);

                var sel = window.getSelection();
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }, 10);
    }else if(that.hasClass("del")){ //删除
        _editor.focus();
        _editor.blur(); //输入表情时禁止输入法

        setTimeout(function(){
            range = window.getSelection().getRangeAt(0);
            range.collapse(false);

            var sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
            document.execCommand("delete");
        }, 10);
    } else if(that.hasClass("lg-face")){ //大表情
        var _img = that.parent().html();
        var _tpl = [
            '<li class="me">\
                <div class="content">\
                    <p class="author">Nice奶思</p>\
                    <div class="msg lgface">'+ _img + '</div>\
                </div>\
                <a class="avatar" href="微聊(好友主页).html"><img src="img/uimg/u__chat-img14.jpg" /></a>\
            </li>'
        ].join("");
        $chatMsgList.append(_tpl);

        wchat_ToBottom();
    }
});

<!-- //微聊消息上墙面板 -->
<div class="wc__chatMsg-panel flex1">
    <div class="wc__slimscroll2">
        <div class="chatMsg-cnt">
            <ul class="clearfix" id="J__chatMsgList">
                <li class="time">2017年12月28日 晚上21:10</li>
                <li class="notice">"<a href="#">Aster</a>"通过扫描"<a href="#">张小龙</a>"分享的二维码加入群聊</li>
                <li class="time">2017年12月28日 晚上23:15</li>
                <li class="notice">"<a href="#">雷军</a>"通过扫描"<a href="#">李彦宏</a>"分享的二维码加入群聊</li>
                <li class="notice">当前群聊人数较多,已显示群成员昵称,同时为了信息安全,请注意聊天隐私</li>

                <li class="time">2017年12月31日 晚上22:30</li>
                <!-- 别人-->
                <li class="others">
                    <a class="avatar" href="好友主页(详细资料).html"><img src="img/uimg/u__chat-img01.jpg" /></a>
                    <div class="content">
                        <p class="author">马云(老子天下第一)</p>
                        <div class="msg">
                            hello 各位女士、先生,欢迎大家来到达摩派,进群后记得修改备注哈~~ 名字+公司/职业/机构 <img class="face" src="img/emotion/face01/29.png"><img class="face" src="img/emotion/face01/71.png"><img class="face" src="img/emotion/face01/75.png">
                        </div>
                    </div>
                </li>
                <!--自己-->
                <li class="me">
                    <div class="content">
                        <p class="author">Nice奶思</p>
                        <div class="msg">
                            么么哒,马总发个红包呗!
                        </div>
                    </div>
                    <a class="avatar" href="好友主页(详细资料).html"><img src="img/uimg/u__chat-img14.jpg" /></a>
                </li>
                <li class="others">
                    <a class="avatar" href="好友主页(详细资料).html"><img src="img/uimg/u__chat-img02.jpg" /></a>
                    <div class="content">
                        <p class="author">MR(马蓉 ▪ ☀☼㈱)</p>
                        <div class="msg">
                            马总,晚上好哇,还木休息呢。我还在景区度假呢,棒棒! <img class="face" src="img/emotion/face01/69.png">
                        </div>
                    </div>
                </li>
                <li class="others">
                    <a class="avatar" href="好友主页(详细资料).html"><img src="img/uimg/u__chat-img02.jpg" /></a>
                    <div class="content">
                        <p class="author">MR(马蓉 ▪ ☀☼㈱)</p>
                        <div class="msg picture">
                            <img class="img__pic" src="img/placeholder/wchat__img03.jpg" />
                        </div>
                    </div>
                </li>
                <li class="others">
                    <a class="avatar" href="好友主页(详细资料).html"><img src="img/uimg/u__chat-img12.jpg" /></a>
                    <div class="content">
                        <p class="author">Flowers(杨迪)</p>
                        <div class="msg">
                            哼,要红包。 <img class="face" src="img/emotion/face01/63.png">
                        </div>
                    </div>
                </li>
                <li class="time">1月1日 早上02:00</li>
                <li class="others">
                    <a class="avatar" href="好友主页(详细资料).html"><img src="img/uimg/u__chat-img04.jpg" /></a>
                    <div class="content">
                        <p class="author">Xlong(张小龙)</p>
                        <div class="msg">
                            小程序后台新增推广功能,支持开发者添加与业务相关的自定义关键词!<br>
                            <a href="https://mp.weixin.qq.com/cgi-bin/wx">https://mp.weixin.qq.com/cgi-bin/wx</a>
                        </div>
                    </div>
                </li>
                <li class="me">
                    <div class="content">
                        <p class="author">Nice奶思</p>
                        <div class="msg">
                            小龙哥好敬业哇,牛牛牛!<img class="face" src="img/emotion/face01/79.png">
                        </div>
                    </div>
                    <a class="avatar" href="好友主页(详细资料).html"><img src="img/uimg/u__chat-img14.jpg" /></a>
                </li>
                <li class="me">
                    <div class="content">
                        <p class="author">Nice奶思</p>
                        <div class="msg video">
                            <img class="img__video" src="img/placeholder/wchat__video02-poster.jpg" videoUrl="img/placeholder/wchat__video02-Y7qk5uVcNcFJIY8O4mKzDw.mp4" />
                        </div>
                    </div>
                    <a class="avatar" href="好友主页(详细资料).html">
                        <img src="img/uimg/u__chat-img14.jpg" />
                    </a>
                </li>
                <li class="time">2月25日 早上09:48</li>
                <li class="others">
                    <a class="avatar" href="好友主页(详细资料).html"><img src="img/uimg/u__chat-img06.jpg" /></a>
                    <div class="content">
                        <p class="author">Robin(李彦宏)</p>
                        <div class="msg">
                            早上好,各位,这次人机交互线下活动的视频及PPT预计明天可以公开啦 <img class="face" src="img/emotion/face01/4.png">
                        </div>
                    </div>
                </li>
                <li class="others">
                    <a class="avatar" href="好友主页(详细资料).html"><img src="img/uimg/u__chat-img15.jpg" /></a>
                    <div class="content">
                        <p class="author">King(李嘉诚)</p>
                        <div class="msg">
                            这个不错,支持下~ <img class="face" src="img/emotion/face01/42.png">
                        </div>
                    </div>
                </li>
                <li class="time">3月12日 下午14:28</li>
                <li class="others">
                    <a class="avatar" href="好友主页(详细资料).html"><img src="img/uimg/u__chat-img03.jpg" /></a>
                    <div class="content">
                        <p class="author">Jay(周杰伦)</p>
                        <div class="msg">
                            我的新专辑《告白气球》将于6.1上线,到时希望大家多多支持啦~ <img class="face" src="img/emotion/face01/66.png">
                        </div>
                    </div>
                </li>
                <li class="others">
                    <a class="avatar" href="好友主页(详细资料).html"><img src="img/uimg/u__chat-img11.jpg" /></a>
                    <div class="content">
                        <p class="author">Luci(王巧巧)</p>
                        <div class="msg picture">
                            <img class="img__pic" src="img/placeholder/wchat__img01.jpg" />
                        </div>
                    </div>
                </li>
                <li class="time">"马云(老子天下第一)" 撤回了一条消息</li>
                <li class="others">
                    <a class="avatar" href="好友主页(详细资料).html"><img src="img/uimg/u__chat-img11.jpg" /></a>
                    <div class="content">
                        <p class="author">Luci(王巧巧)</p>
                        <div class="msg video">
                            <img class="img__video" src="img/placeholder/wchat__video01-poster.jpg" videoUrl="img/placeholder/wchat__video01-Y7qk5uVcNcFJIY8O4mKzDw.mp4" />
                        </div>
                    </div>
                </li>
                <li class="time">"Luci(王巧巧)" 已被移出群聊</li>
                <li class="me">
                    <div class="content">
                        <p class="author">Nice奶思</p>
                        <div class="msg picture">
                            <img class="img__pic" src="img/placeholder/wchat__img02.jpg">
                        </div>
                    </div>
                    <a class="avatar" href="好友主页(详细资料).html"><img src="img/uimg/u__chat-img14.jpg" /></a>
                </li>
                <li class="me">
                    <div class="content">
                        <p class="author">Nice奶思</p>
                        <div class="msg">
                            北京新世纪饭店发放福利啦,免费领取VIP会员,大家快去参与吧。
                        </div>
                    </div>
                    <a class="avatar" href="好友主页(详细资料).html"><img src="img/uimg/u__chat-img14.jpg" /></a>
                </li>
            </ul>
        </div>
    </div>
</div>

Server类代码如下:

Server类代码如下:

亚洲必赢官网 29

 

package com.swift.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.google.gson.Gson;
import com.swift.jdbc.DBAdd;
import com.swift.jdbc.DBLogin;
import com.swift.other.User;
import com.swift.util.Info;

public class Server {

    boolean started = false;
    ServerSocket ss = null;
    Socket s = null;
    List<Client> clients = new ArrayList<Client>();
    Vector<String> list = new Vector<String>();

    public static void main(String[] args) {
        new Server().fun();
    }

    private void fun() {
        try {
            ss = new ServerSocket(8888);
            started = true;
        } catch (BindException e) {
            System.out.println("端口使用中......");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            while (started) {
                s = ss.accept();
                System.out.println("a client connected success");
                Client c = new Client(s);
                clients.add(c);
                new Thread(c).start();

            }
        } catch (EOFException e) {
            System.out.println("client has closed.");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ss.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    class Client implements Runnable {

        public Socket s;
        public DataInputStream dis;
        public DataOutputStream dos;
        private boolean connected = false;

        public Client(Socket s) {
            this.s = s;
            try {
                this.dis = new DataInputStream(s.getInputStream());
                this.dos = new DataOutputStream(s.getOutputStream());
                connected = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                while (connected) {
                    // 接收客户端请求
                    String json = dis.readUTF();
                    Gson gson = new Gson();
                    Info info = gson.fromJson(json, Info.class);
                    if (info.getState().equals("login")) {

                        String phone = info.getPhone();
                        String password = info.getPassword();
                        System.out.println(phone);
                        System.out.println(password);

                        User user = new User(phone, password);
                        boolean login = DBLogin.login(user);
                        if (login) {
                            dos.writeUTF("success");
                            dos.flush();
                            String userName = dis.readUTF();
                            // 添加进好友列表Vector
                            list.addElement(userName);

                            System.out.println();
                            // 每当有成功登陆就向各个客户端发送完整列表
                            for (int i = 0; i < clients.size(); i++) {
                                Client c = clients.get(i);
                                System.out.println(c.s.getPort());
                                for (int j = 0; j < list.size(); j++) {
                                    String name = list.get(j);
                                    System.out.println(name);
                                    String json_name = "{\"state\":\"friends\",\"msg\":\"" + name + "\"}";
                                    c.send(json_name);
                                }
                            }

                        } else {
                            dos.writeUTF("fail");
                            dos.flush();
                        }

                    } else if (info.getState().equals("reg")) {
                        String phone = info.getPhone();
                        String password = info.getPassword();
                        System.out.println(phone);
                        System.out.println(password);

                        User user = new User(phone, password);
                        boolean flag = DBAdd.add(user);
                        if (flag) {
                            dos.writeUTF("success");
                        }else {
                            dos.writeUTF("fail");
                        }
                    } else if (info.getState().equals("chat")) {
                        System.out.println(json);
                        for (int i = 0; i < clients.size(); i++) {
                            Client c = clients.get(i);
                            c.send(json);
                        }
                    }

                }
            } catch (SocketException e) {
                System.out.println("一个登陆窗已经关闭....");
            } catch (EOFException e) {
                System.out.println("a client has been closed,can't read message from it.");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (s != null) {
                    try {
                        s.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (dis != null) {
                    try {
                        dis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (dos != null) {
                    try {
                        dos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        private void send(String str) {
            try {
                this.dos.writeUTF(str);
                this.dos.flush();
            } catch (SocketException e) {
                clients.remove(this);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
package com.swift.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.google.gson.Gson;
import com.swift.jdbc.DBAdd;
import com.swift.jdbc.DBLogin;
import com.swift.other.User;
import com.swift.util.Info;

public class Server {

    boolean started = false;
    ServerSocket ss = null;
    Socket s = null;
    List<Client> clients = new ArrayList<Client>();
    Vector<String> list = new Vector<String>();

    public static void main(String[] args) {
        new Server().fun();
    }

    private void fun() {
        try {
            ss = new ServerSocket(8888);
            started = true;
        } catch (BindException e) {
            System.out.println("端口使用中......");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            while (started) {
                s = ss.accept();
                System.out.println("a client connected success");
                Client c = new Client(s);
                clients.add(c);
                new Thread(c).start();

            }
        } catch (EOFException e) {
            System.out.println("client has closed.");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ss.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    class Client implements Runnable {

        public Socket s;
        public DataInputStream dis;
        public DataOutputStream dos;
        private boolean connected = false;

        public Client(Socket s) {
            this.s = s;
            try {
                this.dis = new DataInputStream(s.getInputStream());
                this.dos = new DataOutputStream(s.getOutputStream());
                connected = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                while (connected) {
                    // 接收客户端请求
                    String json = dis.readUTF();
                    Gson gson = new Gson();
                    Info info = gson.fromJson(json, Info.class);
                    if (info.getState().equals("login")) {

                        String phone = info.getPhone();
                        String password = info.getPassword();
                        System.out.println(phone);
                        System.out.println(password);

                        User user = new User(phone, password);
                        boolean login = DBLogin.login(user);
                        if (login) {
                            dos.writeUTF("success");
                            dos.flush();
                            String userName = dis.readUTF();
                            // 添加进好友列表Vector
                            list.addElement(userName);

                            System.out.println();
                            // 每当有成功登陆就向各个客户端发送完整列表
                            for (int i = 0; i < clients.size(); i++) {
                                Client c = clients.get(i);
                                System.out.println(c.s.getPort());
                                for (int j = 0; j < list.size(); j++) {
                                    String name = list.get(j);
                                    System.out.println(name);
                                    String json_name = "{\"state\":\"friends\",\"msg\":\"" + name + "\"}";
                                    c.send(json_name);
                                }
                            }

                        } else {
                            dos.writeUTF("fail");
                            dos.flush();
                        }

                    } else if (info.getState().equals("reg")) {
                        String phone = info.getPhone();
                        String password = info.getPassword();
                        System.out.println(phone);
                        System.out.println(password);

                        User user = new User(phone, password);
                        boolean flag = DBAdd.add(user);
                        if (flag) {
                            dos.writeUTF("success");
                        }else {
                            dos.writeUTF("fail");
                        }
                    } else if (info.getState().equals("chat")) {
                        System.out.println(json);
                        for (int i = 0; i < clients.size(); i++) {
                            Client c = clients.get(i);
                            c.send(json);
                        }
                    }

                }
            } catch (SocketException e) {
                System.out.println("一个登陆窗已经关闭....");
            } catch (EOFException e) {
                System.out.println("a client has been closed,can't read message from it.");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (s != null) {
                    try {
                        s.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (dis != null) {
                    try {
                        dis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (dos != null) {
                    try {
                        dos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        private void send(String str) {
            try {
                this.dos.writeUTF(str);
                this.dos.flush();
            } catch (SocketException e) {
                clients.remove(this);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

亚洲必赢官网 30

亚洲必赢官网 31

增产的工具类Info,通过info对象的get方法把收获服务端获得的各类字符串直接归类了。

增加产量的工具类Info,通过info对象的get方法把收获服务端得到的种种字符串直接归类了。

亚洲必赢官网 32

亚洲必赢官网 33

Info类代码如下:

Info类代码如下:

亚洲必赢官网 34

亚洲必赢官网 35

package com.swift.util;

public class Info {
    private String state;
    private String msg;
    private String phone;
    private String password;
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }

}
package com.swift.util;

public class Info {
    private String state;
    private String msg;
    private String phone;
    private String password;
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }

}

亚洲必赢官网 36

重构了登入窗口的登录和挂号请求

重构了登录窗口的登录和挂号请求

 

登录窗口的代码如下:

登入窗口的代码如下:

package com.swift.frame;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.TitledBorder;

import com.swift.util.Center;

public class LoginDialog extends JDialog {

    private static final long serialVersionUID = 1L;
    private JPasswordField passwordField_2;
    private JPasswordField passwordField_1;
    private JTextField textField_2;
    private JTextField textField;

    Socket s;
    DataOutputStream dos;
    DataInputStream dis;

    public static void main(String args[]) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);

        try {
            UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        } catch (InstantiationException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        } catch (UnsupportedLookAndFeelException e1) {
            e1.printStackTrace();
        }

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    LoginDialog dialog = new LoginDialog();
                    dialog.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent e) {
                            System.exit(0);
                        }
                    });
                    dialog.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public LoginDialog() {
        super();
        setResizable(false);
        setTitle("在线聊天登录框");
        getContentPane().setLayout(null);
        setBounds(100, 100, 427, 301);// 注册时高度为578,不注册是301

        // 设置窗口居中
        this.setLocation(Center.getPoint(this.getSize()));

        final JTextField textField_1 = new JTextField();
        textField_1.setBounds(148, 90, 192, 42);
        getContentPane().add(textField_1);

        final JLabel label = new JLabel();
        label.setText("帐    号");
        label.setBounds(76, 102, 66, 18);
        getContentPane().add(label);

        final JLabel label_1 = new JLabel();
        label_1.setText("密    码");
        label_1.setBounds(76, 167, 66, 18);
        getContentPane().add(label_1);

        final JPasswordField passwordField = new JPasswordField();
        passwordField.setBounds(148, 155, 192, 42);
        getContentPane().add(passwordField);

        final JButton button_1 = new JButton();
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {

                String phone = new String(textField_1.getText()).trim();
                String password = new String(passwordField.getPassword()).trim();
                if (!phone.equals("") && !password.equals("")) {
                    try {
                        String json_login = "{\"state\":\"login\",\"phone\":\"" + phone + "\",\"password\":\""
                                + password + "\"}";
                        dos.writeUTF(json_login);
                        dos.flush();
                        String flag = dis.readUTF();
                        if (flag.equals("success")) {
                            javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "登录成功");
                            // 把登陆成功的用户发送给服务端,作为好友列表信息
                            dos.writeUTF(phone);
                            dos.flush();
                            // 登陆窗消失
                            LoginDialog.this.dispose();
                            // 好友列表窗出现
                            new FriendsFrame(phone, s);

                        } else if (flag.equals("fail")) {
                            javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "登录失败");
                        }
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                } else {
                    javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "用户名密码必须填写...");
                    return;
                }
            }
        });
        button_1.setText("登录");
        button_1.setBounds(230, 222, 106, 36);
        getContentPane().add(button_1);

        final JButton button = new JButton();
        button.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                if (LoginDialog.this.getHeight() == 301) {
                    LoginDialog.this.setSize(427, 578);
                } else {
                    LoginDialog.this.setSize(427, 301);
                }
                // 设置窗口不断居中
                LoginDialog.this.setLocation(Center.getPoint(LoginDialog.this.getSize()));
            }
        });
        button.setText("注册");
        button.setBounds(76, 222, 106, 36);
        getContentPane().add(button);

        final JPanel panel = new JPanel();
        panel.setLayout(null);
        panel.setBorder(new TitledBorder(null, "注册用户", TitledBorder.DEFAULT_JUSTIFICATION,
                TitledBorder.DEFAULT_POSITION, null, null));
        panel.setBounds(10, 278, 401, 226);
        getContentPane().add(panel);

        final JLabel label_2 = new JLabel();
        label_2.setBounds(44, 41, 65, 18);
        label_2.setText("手机号:");
        panel.add(label_2);

        textField = new JTextField();
        textField.setBounds(115, 35, 225, 30);
        panel.add(textField);

        final JButton button_2 = new JButton();
        button_2.setText("发送验证");
        button_2.setBounds(243, 75, 97, 30);
        panel.add(button_2);

        textField_2 = new JTextField();
        textField_2.setBounds(115, 104, 95, 30);
        panel.add(textField_2);

        final JLabel label_3 = new JLabel();
        label_3.setText("验证码:");
        label_3.setBounds(44, 110, 65, 18);
        panel.add(label_3);

        passwordField_1 = new JPasswordField();
        passwordField_1.setBounds(115, 143, 231, 30);
        panel.add(passwordField_1);

        passwordField_2 = new JPasswordField();
        passwordField_2.setBounds(115, 175, 231, 30);
        panel.add(passwordField_2);

        final JLabel label_4 = new JLabel();
        label_4.setText("密        码:");
        label_4.setBounds(44, 149, 65, 18);
        panel.add(label_4);

        final JLabel label_5 = new JLabel();
        label_5.setText("验证密码:");
        label_5.setBounds(44, 181, 65, 18);
        panel.add(label_5);

        final JButton button_3 = new JButton();
        button_3.setBounds(47, 510, 97, 30);
        getContentPane().add(button_3);
        button_3.setText("放弃");

        final JButton button_4 = new JButton();
        button_4.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {

                String phone = textField.getText();
                String password = null;
                String str1 = new String(passwordField_1.getPassword()).trim();
                String str2 = new String(passwordField_2.getPassword()).trim();
                if (!phone.equals("") && !str1.equals("") && !str2.equals("")) {
                    if (str1.equals(str2)) {
                        password = new String(passwordField_2.getPassword()).trim();
                        try {
                            String json_reg = "{\"state\":\"reg\",\"phone\":\"" + phone + "\",\"password\":\""
                                    + password + "\"}";
                            dos.writeUTF(json_reg);
                            dos.flush();
                            String flag = dis.readUTF();
                            if (flag.equals("success")) {
                                javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "注册成功...");
                                textField.setText("");
                                passwordField_1.setText("");
                                passwordField_2.setText("");
                            } else {
                                javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "注册失败...");
                            }
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    } else {
                        javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "输入密码不一致...");
                        System.out.println("输入密码不一致...");
                        passwordField_1.setText("");
                        passwordField_2.setText("");
                    }

                } else {
                    javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "用户名密码必须填写...");
                    return;
                }
            }
        });

        button_4.setBounds(262, 510, 97, 30);
        getContentPane().add(button_4);
        button_4.setText("注册用户");

        connect();

    }

    public void connect() {
        try {
            s = new Socket("127.0.0.1", 8888);// 以本机做server
            System.out.println("一个客户端登陆中....!");
            dos = new DataOutputStream(s.getOutputStream());
            dis = new DataInputStream(s.getInputStream());

        } catch (ConnectException e) {
            System.out.println("服务端异常.........");
            System.out.println("请确认服务端是否开启.........");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
package com.swift.frame;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.TitledBorder;

import com.swift.util.Center;

public class LoginDialog extends JDialog {

    private static final long serialVersionUID = 1L;
    private JPasswordField passwordField_2;
    private JPasswordField passwordField_1;
    private JTextField textField_2;
    private JTextField textField;

    Socket s;
    DataOutputStream dos;
    DataInputStream dis;

    public static void main(String args[]) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);

        try {
            UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        } catch (InstantiationException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        } catch (UnsupportedLookAndFeelException e1) {
            e1.printStackTrace();
        }

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    LoginDialog dialog = new LoginDialog();
                    dialog.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent e) {
                            System.exit(0);
                        }
                    });
                    dialog.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public LoginDialog() {
        super();
        setResizable(false);
        setTitle("在线聊天登录框");
        getContentPane().setLayout(null);
        setBounds(100, 100, 427, 301);// 注册时高度为578,不注册是301

        // 设置窗口居中
        this.setLocation(Center.getPoint(this.getSize()));

        final JTextField textField_1 = new JTextField();
        textField_1.setBounds(148, 90, 192, 42);
        getContentPane().add(textField_1);

        final JLabel label = new JLabel();
        label.setText("帐    号");
        label.setBounds(76, 102, 66, 18);
        getContentPane().add(label);

        final JLabel label_1 = new JLabel();
        label_1.setText("密    码");
        label_1.setBounds(76, 167, 66, 18);
        getContentPane().add(label_1);

        final JPasswordField passwordField = new JPasswordField();
        passwordField.setBounds(148, 155, 192, 42);
        getContentPane().add(passwordField);

        final JButton button_1 = new JButton();
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {

                String phone = new String(textField_1.getText()).trim();
                String password = new String(passwordField.getPassword()).trim();
                if (!phone.equals("") && !password.equals("")) {
                    try {
                        String json_login = "{\"state\":\"login\",\"phone\":\"" + phone + "\",\"password\":\""
                                + password + "\"}";
                        dos.writeUTF(json_login);
                        dos.flush();
                        String flag = dis.readUTF();
                        if (flag.equals("success")) {
                            javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "登录成功");
                            // 把登陆成功的用户发送给服务端,作为好友列表信息
                            dos.writeUTF(phone);
                            dos.flush();
                            // 登陆窗消失
                            LoginDialog.this.dispose();
                            // 好友列表窗出现
                            new FriendsFrame(phone, s);

                        } else if (flag.equals("fail")) {
                            javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "登录失败");
                        }
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                } else {
                    javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "用户名密码必须填写...");
                    return;
                }
            }
        });
        button_1.setText("登录");
        button_1.setBounds(230, 222, 106, 36);
        getContentPane().add(button_1);

        final JButton button = new JButton();
        button.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                if (LoginDialog.this.getHeight() == 301) {
                    LoginDialog.this.setSize(427, 578);
                } else {
                    LoginDialog.this.setSize(427, 301);
                }
                // 设置窗口不断居中
                LoginDialog.this.setLocation(Center.getPoint(LoginDialog.this.getSize()));
            }
        });
        button.setText("注册");
        button.setBounds(76, 222, 106, 36);
        getContentPane().add(button);

        final JPanel panel = new JPanel();
        panel.setLayout(null);
        panel.setBorder(new TitledBorder(null, "注册用户", TitledBorder.DEFAULT_JUSTIFICATION,
                TitledBorder.DEFAULT_POSITION, null, null));
        panel.setBounds(10, 278, 401, 226);
        getContentPane().add(panel);

        final JLabel label_2 = new JLabel();
        label_2.setBounds(44, 41, 65, 18);
        label_2.setText("手机号:");
        panel.add(label_2);

        textField = new JTextField();
        textField.setBounds(115, 35, 225, 30);
        panel.add(textField);

        final JButton button_2 = new JButton();
        button_2.setText("发送验证");
        button_2.setBounds(243, 75, 97, 30);
        panel.add(button_2);

        textField_2 = new JTextField();
        textField_2.setBounds(115, 104, 95, 30);
        panel.add(textField_2);

        final JLabel label_3 = new JLabel();
        label_3.setText("验证码:");
        label_3.setBounds(44, 110, 65, 18);
        panel.add(label_3);

        passwordField_1 = new JPasswordField();
        passwordField_1.setBounds(115, 143, 231, 30);
        panel.add(passwordField_1);

        passwordField_2 = new JPasswordField();
        passwordField_2.setBounds(115, 175, 231, 30);
        panel.add(passwordField_2);

        final JLabel label_4 = new JLabel();
        label_4.setText("密        码:");
        label_4.setBounds(44, 149, 65, 18);
        panel.add(label_4);

        final JLabel label_5 = new JLabel();
        label_5.setText("验证密码:");
        label_5.setBounds(44, 181, 65, 18);
        panel.add(label_5);

        final JButton button_3 = new JButton();
        button_3.setBounds(47, 510, 97, 30);
        getContentPane().add(button_3);
        button_3.setText("放弃");

        final JButton button_4 = new JButton();
        button_4.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {

                String phone = textField.getText();
                String password = null;
                String str1 = new String(passwordField_1.getPassword()).trim();
                String str2 = new String(passwordField_2.getPassword()).trim();
                if (!phone.equals("") && !str1.equals("") && !str2.equals("")) {
                    if (str1.equals(str2)) {
                        password = new String(passwordField_2.getPassword()).trim();
                        try {
                            String json_reg = "{\"state\":\"reg\",\"phone\":\"" + phone + "\",\"password\":\""
                                    + password + "\"}";
                            dos.writeUTF(json_reg);
                            dos.flush();
                            String flag = dis.readUTF();
                            if (flag.equals("success")) {
                                javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "注册成功...");
                                textField.setText("");
                                passwordField_1.setText("");
                                passwordField_2.setText("");
                            } else {
                                javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "注册失败...");
                            }
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    } else {
                        javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "输入密码不一致...");
                        System.out.println("输入密码不一致...");
                        passwordField_1.setText("");
                        passwordField_2.setText("");
                    }

                } else {
                    javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "用户名密码必须填写...");
                    return;
                }
            }
        });

        button_4.setBounds(262, 510, 97, 30);
        getContentPane().add(button_4);
        button_4.setText("注册用户");

        connect();

    }

    public void connect() {
        try {
            s = new Socket("127.0.0.1", 8888);// 以本机做server
            System.out.println("一个客户端登陆中....!");
            dos = new DataOutputStream(s.getOutputStream());
            dis = new DataInputStream(s.getInputStream());

        } catch (ConnectException e) {
            System.out.println("服务端异常.........");
            System.out.println("请确认服务端是否开启.........");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

对好友列表窗的死循环傻傻等待服务端音讯,实行了重构,通过Gson方法自动判定所收获的Json串消息毕竟是忘年交的换代还是聊天音信的更新。

对好友列表窗的死循环傻傻等待服务端音讯,实行了重构,通过Gson方法自动推断所获得的Json串消息终归是忘年交的换代依旧聊天消息的更新。

好友列表窗代码如下:

好友列表窗代码如下:

package com.swift.frame;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.swift.util.Info;

public class FriendsFrame extends JFrame {

    private static final long serialVersionUID = 1L;
    private Socket s;
    private DataOutputStream dos;
    private DataInputStream dis;
    private boolean connected = false;
    Vector<String> names = new Vector<String>();
    JList<String> list = null;

    public FriendsFrame(String name, Socket socket) {
        super("欢迎 " + ":" + socket.getLocalPort());
        this.s = socket;
        connected = true;
        names.add("登录用户");
        try {
            this.dos = new DataOutputStream(s.getOutputStream());
            this.dis = new DataInputStream(s.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);

        try {
            UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        } catch (InstantiationException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        } catch (UnsupportedLookAndFeelException e1) {
            e1.printStackTrace();
        }

        setBounds(100, 100, 247, 581);
        setVisible(true);
        final JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        getContentPane().add(panel, BorderLayout.NORTH);

        final JLabel label = new JLabel(new ImageIcon("Images/logo.jpg"));
        label.setText("New JLabel");
        panel.add(label, BorderLayout.WEST);
        label.setPreferredSize(new Dimension(74, 74));

        final JPanel panel_1 = new JPanel();
        panel_1.setLayout(new BorderLayout());
        panel.add(panel_1, BorderLayout.CENTER);

        final JLabel advancingSwiftLabel = new JLabel();
        advancingSwiftLabel.setText(name);
        panel_1.add(advancingSwiftLabel, BorderLayout.CENTER);

        final JLabel neverWasterLabel = new JLabel();
        neverWasterLabel.setText("Never waste time any more");
        panel_1.add(neverWasterLabel, BorderLayout.SOUTH);

        final JPanel panel_2 = new JPanel();
        panel_2.setLayout(new BorderLayout());
        getContentPane().add(panel_2, BorderLayout.SOUTH);

        final JPanel panel_3 = new JPanel();
        final FlowLayout flowLayout = new FlowLayout();
        flowLayout.setAlignment(FlowLayout.LEFT);
        panel_3.setLayout(flowLayout);
        panel_2.add(panel_3);

        final JButton button = new JButton();
        panel_3.add(button);
        button.setHorizontalTextPosition(SwingConstants.LEFT);
        button.setHorizontalAlignment(SwingConstants.LEFT);
        button.setText("设置");

        final JButton button_1 = new JButton();
        panel_3.add(button_1);
        button_1.setText("查找");

        final JPanel panel_4 = new JPanel();
        panel_2.add(panel_4, BorderLayout.EAST);

        final JButton button_2 = new JButton();
        panel_4.add(button_2);
        button_2.setText("退出");

        final JTabbedPane tabbedPane = new JTabbedPane();
        getContentPane().add(tabbedPane, BorderLayout.CENTER);

        final JPanel panel_5 = new JPanel();
        tabbedPane.addTab("好友列表", null, panel_5, null);
        list = new JList<String>();

        panel_5.add(list);

        final JPanel panel_6 = new JPanel();
        tabbedPane.addTab("群聊", null, panel_6, null);

        final JPanel panel_7 = new JPanel();
        tabbedPane.addTab("聊天记录", null, panel_7, null);

        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        final JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        final JMenu menu = new JMenu();
        menu.setText("操作");
        menuBar.add(menu);

        final JMenuItem newItemMenuItem = new JMenuItem();
        newItemMenuItem.setText("设置");
        menu.add(newItemMenuItem);

        final JMenuItem newItemMenuItem_1 = new JMenuItem();
        newItemMenuItem_1.setText("空间");
        menu.add(newItemMenuItem_1);

        final JMenuItem newItemMenuItem_2 = new JMenuItem();
        newItemMenuItem_2.setText("邮箱");
        menu.add(newItemMenuItem_2);

        final JMenu menu_1 = new JMenu();
        menu_1.setText("会员");
        menu.add(menu_1);

        final JMenuItem newItemMenuItem_3 = new JMenuItem();
        newItemMenuItem_3.setText("会员官网");
        menu_1.add(newItemMenuItem_3);

        final JMenuItem newItemMenuItem_4 = new JMenuItem();
        newItemMenuItem_4.setText("会员专区");
        menu_1.add(newItemMenuItem_4);

        menu.addSeparator();

        final JMenu menu_2 = new JMenu();
        menu_2.setText("安全");
        menu.add(menu_2);

        final JMenuItem newItemMenuItem_5 = new JMenuItem();
        newItemMenuItem_5.setText("紧急冻结");
        menu_2.add(newItemMenuItem_5);

        final JMenuItem newItemMenuItem_6 = new JMenuItem();
        newItemMenuItem_6.setText("密码保护");
        menu_2.add(newItemMenuItem_6);

        final JMenuItem newItemMenuItem_7 = new JMenuItem();
        newItemMenuItem_7.setText("退出");
        menu.add(newItemMenuItem_7);
        final FlowLayout flowLayout_1 = new FlowLayout();
        flowLayout_1.setAlignment(FlowLayout.RIGHT);

        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                disconnect();
                System.exit(0);
            }
        });

        // 调用傻傻的等待接收列表信息
        new Thread(new WaitingReceive()).start();
        // 双击激活聊天对话框
        list.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    new ChatFrame(s);
                }
            }
        });

    }

    public void disconnect() {
        try {
            if (dos != null)
                dos.close();
            if (dis != null)
                dis.close();
            if (s != null)
                s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class WaitingReceive implements Runnable {

        @Override
        public void run() {
            try {
                while (connected) {
                    String json = dis.readUTF();
                    Gson gson = new Gson();
                    Info info = gson.fromJson(json, Info.class);
                    System.out.println(json + "~~~~~~~~~~~~~~~~~~~~~~~~");
                    if (info.getState().equals("friends")) {
                        int flag = 0;
                        for (int i = 0; i < names.size(); i++) {
                            if (info.getMsg().equals(names.get(i))) {
                                flag = 1;
                            }
                        }
                        if (flag == 0) {
                            names.add(info.getMsg());
                        }
                        list.setListData(names);
                    }
                    if(info.getState().equals("chat")) {
                        ChatFrame.showTa(info.getMsg());

                        System.out.println(info.getMsg());
                    }

                }
            } catch (SocketException e) {
                System.out.println("a client has been closed!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * WindowBuilder generated method.<br>
     * Please don't remove this method or its invocations.<br>
     * It used by WindowBuilder to associate the {@link javax.swing.JPopupMenu} with
     * parent.
     */
    private static void addPopup(Component component, final JPopupMenu popup) {
        component.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger())
                    showMenu(e);
            }

            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger())
                    showMenu(e);
            }

            private void showMenu(MouseEvent e) {
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        });
    }
}
package com.swift.frame;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.swift.util.Info;

public class FriendsFrame extends JFrame {

    private static final long serialVersionUID = 1L;
    private Socket s;
    private DataOutputStream dos;
    private DataInputStream dis;
    private boolean connected = false;
    Vector<String> names = new Vector<String>();
    JList<String> list = null;

    public FriendsFrame(String name, Socket socket) {
        super("欢迎 " + ":" + socket.getLocalPort());
        this.s = socket;
        connected = true;
        names.add("登录用户");
        try {
            this.dos = new DataOutputStream(s.getOutputStream());
            this.dis = new DataInputStream(s.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);

        try {
            UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        } catch (InstantiationException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        } catch (UnsupportedLookAndFeelException e1) {
            e1.printStackTrace();
        }

        setBounds(100, 100, 247, 581);
        setVisible(true);
        final JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        getContentPane().add(panel, BorderLayout.NORTH);

        final JLabel label = new JLabel(new ImageIcon("Images/logo.jpg"));
        label.setText("New JLabel");
        panel.add(label, BorderLayout.WEST);
        label.setPreferredSize(new Dimension(74, 74));

        final JPanel panel_1 = new JPanel();
        panel_1.setLayout(new BorderLayout());
        panel.add(panel_1, BorderLayout.CENTER);

        final JLabel advancingSwiftLabel = new JLabel();
        advancingSwiftLabel.setText(name);
        panel_1.add(advancingSwiftLabel, BorderLayout.CENTER);

        final JLabel neverWasterLabel = new JLabel();
        neverWasterLabel.setText("Never waste time any more");
        panel_1.add(neverWasterLabel, BorderLayout.SOUTH);

        final JPanel panel_2 = new JPanel();
        panel_2.setLayout(new BorderLayout());
        getContentPane().add(panel_2, BorderLayout.SOUTH);

        final JPanel panel_3 = new JPanel();
        final FlowLayout flowLayout = new FlowLayout();
        flowLayout.setAlignment(FlowLayout.LEFT);
        panel_3.setLayout(flowLayout);
        panel_2.add(panel_3);

        final JButton button = new JButton();
        panel_3.add(button);
        button.setHorizontalTextPosition(SwingConstants.LEFT);
        button.setHorizontalAlignment(SwingConstants.LEFT);
        button.setText("设置");

        final JButton button_1 = new JButton();
        panel_3.add(button_1);
        button_1.setText("查找");

        final JPanel panel_4 = new JPanel();
        panel_2.add(panel_4, BorderLayout.EAST);

        final JButton button_2 = new JButton();
        panel_4.add(button_2);
        button_2.setText("退出");

        final JTabbedPane tabbedPane = new JTabbedPane();
        getContentPane().add(tabbedPane, BorderLayout.CENTER);

        final JPanel panel_5 = new JPanel();
        tabbedPane.addTab("好友列表", null, panel_5, null);
        list = new JList<String>();

        panel_5.add(list);

        final JPanel panel_6 = new JPanel();
        tabbedPane.addTab("群聊", null, panel_6, null);

        final JPanel panel_7 = new JPanel();
        tabbedPane.addTab("聊天记录", null, panel_7, null);

        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        final JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        final JMenu menu = new JMenu();
        menu.setText("操作");
        menuBar.add(menu);

        final JMenuItem newItemMenuItem = new JMenuItem();
        newItemMenuItem.setText("设置");
        menu.add(newItemMenuItem);

        final JMenuItem newItemMenuItem_1 = new JMenuItem();
        newItemMenuItem_1.setText("空间");
        menu.add(newItemMenuItem_1);

        final JMenuItem newItemMenuItem_2 = new JMenuItem();
        newItemMenuItem_2.setText("邮箱");
        menu.add(newItemMenuItem_2);

        final JMenu menu_1 = new JMenu();
        menu_1.setText("会员");
        menu.add(menu_1);

        final JMenuItem newItemMenuItem_3 = new JMenuItem();
        newItemMenuItem_3.setText("会员官网");
        menu_1.add(newItemMenuItem_3);

        final JMenuItem newItemMenuItem_4 = new JMenuItem();
        newItemMenuItem_4.setText("会员专区");
        menu_1.add(newItemMenuItem_4);

        menu.addSeparator();

        final JMenu menu_2 = new JMenu();
        menu_2.setText("安全");
        menu.add(menu_2);

        final JMenuItem newItemMenuItem_5 = new JMenuItem();
        newItemMenuItem_5.setText("紧急冻结");
        menu_2.add(newItemMenuItem_5);

        final JMenuItem newItemMenuItem_6 = new JMenuItem();
        newItemMenuItem_6.setText("密码保护");
        menu_2.add(newItemMenuItem_6);

        final JMenuItem newItemMenuItem_7 = new JMenuItem();
        newItemMenuItem_7.setText("退出");
        menu.add(newItemMenuItem_7);
        final FlowLayout flowLayout_1 = new FlowLayout();
        flowLayout_1.setAlignment(FlowLayout.RIGHT);

        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                disconnect();
                System.exit(0);
            }
        });

        // 调用傻傻的等待接收列表信息
        new Thread(new WaitingReceive()).start();
        // 双击激活聊天对话框
        list.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    new ChatFrame(s);
                }
            }
        });

    }

    public void disconnect() {
        try {
            if (dos != null)
                dos.close();
            if (dis != null)
                dis.close();
            if (s != null)
                s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class WaitingReceive implements Runnable {

        @Override
        public void run() {
            try {
                while (connected) {
                    String json = dis.readUTF();
                    Gson gson = new Gson();
                    Info info = gson.fromJson(json, Info.class);
                    System.out.println(json + "~~~~~~~~~~~~~~~~~~~~~~~~");
                    if (info.getState().equals("friends")) {
                        int flag = 0;
                        for (int i = 0; i < names.size(); i++) {
                            if (info.getMsg().equals(names.get(i))) {
                                flag = 1;
                            }
                        }
                        if (flag == 0) {
                            names.add(info.getMsg());
                        }
                        list.setListData(names);
                    }
                    if(info.getState().equals("chat")) {
                        ChatFrame.showTa(info.getMsg());

                        System.out.println(info.getMsg());
                    }

                }
            } catch (SocketException e) {
                System.out.println("a client has been closed!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * WindowBuilder generated method.<br>
     * Please don't remove this method or its invocations.<br>
     * It used by WindowBuilder to associate the {@link javax.swing.JPopupMenu} with
     * parent.
     */
    private static void addPopup(Component component, final JPopupMenu popup) {
        component.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger())
                    showMenu(e);
            }

            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger())
                    showMenu(e);
            }

            private void showMenu(MouseEvent e) {
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        });
    }
}

对聊天窗非常实行了处理,开掘聊天窗与好友列表窗同时傻傻等待服务端新闻,会引发争执,聊天窗后于好友窗张开所以接不到别的消息。

对聊天窗非常举办了拍卖,开采聊天窗与好友列表窗同时傻傻等待服务端音信,会掀起冲突,聊天窗后于好友窗张开所以接不到其余音讯。

所以将聊天窗的死循环去掉,而扩充2个static静态方法showTa()用来在聊天窗之外供好友窗通过类名.(点)的法门调用,以更换ta(textArea)中的内容。

因而将聊天窗的死循环去掉,而扩展1个static静态方法showTa()用来在聊天窗之外供好友窗通过类名.(点)的章程调用,以退换ta(textArea)中的内容。

聊天窗代码如下:

聊天窗代码如下:

package com.swift.frame;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ChatFrame extends JFrame {

    private static final long serialVersionUID = -118470059355655240L;
    private Socket s;
    private DataOutputStream dos;
    private DataInputStream dis;
    private boolean connected = false;
    JLabel label_shang = new JLabel();
    JLabel label_xia = new JLabel();
    JTextField tf = new JTextField(38);
    public static JTextArea ta = new JTextArea(15, 45);
    JButton button = new JButton();
    String tfText1 = null;

    public ChatFrame(Socket socket) {
        setBounds(200, 200, 500, 400);
        setTitle("客户端聊天工具 —— 1.4");
        // 对窗口进行大的布局,分为三行一列,在pBasic面板上添加三个面板shang zhong xia
        JPanel pBasic = new JPanel();
        pBasic.setLayout(new BorderLayout());// 不设置默认也是这种布局模式
        setContentPane(pBasic);// 把面板放在窗口上,不记得用this.关键字
        JPanel shang = new JPanel();
        JPanel zhong = new JPanel();
        JPanel xia = new JPanel();
        // 设置JPanel面板的大小
        shang.setSize(470, 25);
        zhong.setSize(470, 180);
        xia.setSize(470, 40);
        pBasic.add(shang, BorderLayout.NORTH);
        pBasic.add(zhong, BorderLayout.CENTER);
        pBasic.add(xia, BorderLayout.SOUTH);
        shang.setBackground(Color.red);
        zhong.setBackground(Color.yellow);
        xia.setBackground(Color.blue);

        label_shang.setText("聊天记录");
        shang.add(label_shang);
        ta.setLineWrap(true);// 自动换行
        JScrollPane scroll = new JScrollPane(ta);// 增加滚动条,以便不增加行数
        zhong.add(scroll);
        label_xia.setText("输入信息");
        xia.add(label_xia, BorderLayout.WEST);
        /*
         * 增加功能,窗口监听事件,窗口打开时设置光标焦点在tf文本域中
         */
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent e) {
                tf.requestFocus();
            }
        });
        xia.add(tf, BorderLayout.CENTER);
        button.setText("发送");
        xia.add(button, BorderLayout.EAST);

        button.addActionListener(new MyListener());
        tf.addActionListener(new MyListener());
        pack();

        setVisible(true);
        // 创建窗体直接调用连接服务器
        this.s = socket;
        connected = true;
        try {
            dos = new DataOutputStream(s.getOutputStream());
            dis = new DataInputStream(s.getInputStream());
        } catch (ConnectException e) {
            System.out.println("服务端异常.........");
            System.out.println("请确认服务端是否开启.........");
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    }

    class MyListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            tfText1 = tf.getText();
            tf.setText("");
            // 当回车或发送按钮时,tfText发送到服务器
            String json_chat = "{\"state\":\"chat\",\"msg\":\"" + tfText1 + "\"}";
            try {
                dos.writeUTF(json_chat);
                dos.flush();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }

    public static void showTa(String msg) {
        ta.setText(ta.getText()+msg+ "\r\n");
    }

}
package com.swift.frame;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ChatFrame extends JFrame {

    private static final long serialVersionUID = -118470059355655240L;
    private Socket s;
    private DataOutputStream dos;
    private DataInputStream dis;
    private boolean connected = false;
    JLabel label_shang = new JLabel();
    JLabel label_xia = new JLabel();
    JTextField tf = new JTextField(38);
    public static JTextArea ta = new JTextArea(15, 45);
    JButton button = new JButton();
    String tfText1 = null;

    public ChatFrame(Socket socket) {
        setBounds(200, 200, 500, 400);
        setTitle("客户端聊天工具 —— 1.4");
        // 对窗口进行大的布局,分为三行一列,在pBasic面板上添加三个面板shang zhong xia
        JPanel pBasic = new JPanel();
        pBasic.setLayout(new BorderLayout());// 不设置默认也是这种布局模式
        setContentPane(pBasic);// 把面板放在窗口上,不记得用this.关键字
        JPanel shang = new JPanel();
        JPanel zhong = new JPanel();
        JPanel xia = new JPanel();
        // 设置JPanel面板的大小
        shang.setSize(470, 25);
        zhong.setSize(470, 180);
        xia.setSize(470, 40);
        pBasic.add(shang, BorderLayout.NORTH);
        pBasic.add(zhong, BorderLayout.CENTER);
        pBasic.add(xia, BorderLayout.SOUTH);
        shang.setBackground(Color.red);
        zhong.setBackground(Color.yellow);
        xia.setBackground(Color.blue);

        label_shang.setText("聊天记录");
        shang.add(label_shang);
        ta.setLineWrap(true);// 自动换行
        JScrollPane scroll = new JScrollPane(ta);// 增加滚动条,以便不增加行数
        zhong.add(scroll);
        label_xia.setText("输入信息");
        xia.add(label_xia, BorderLayout.WEST);
        /*
         * 增加功能,窗口监听事件,窗口打开时设置光标焦点在tf文本域中
         */
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent e) {
                tf.requestFocus();
            }
        });
        xia.add(tf, BorderLayout.CENTER);
        button.setText("发送");
        xia.add(button, BorderLayout.EAST);

        button.addActionListener(new MyListener());
        tf.addActionListener(new MyListener());
        pack();

        setVisible(true);
        // 创建窗体直接调用连接服务器
        this.s = socket;
        connected = true;
        try {
            dos = new DataOutputStream(s.getOutputStream());
            dis = new DataInputStream(s.getInputStream());
        } catch (ConnectException e) {
            System.out.println("服务端异常.........");
            System.out.println("请确认服务端是否开启.........");
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    }

    class MyListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            tfText1 = tf.getText();
            tf.setText("");
            // 当回车或发送按钮时,tfText发送到服务器
            String json_chat = "{\"state\":\"chat\",\"msg\":\"" + tfText1 + "\"}";
            try {
                dos.writeUTF(json_chat);
                dos.flush();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }

    public static void showTa(String msg) {
        ta.setText(ta.getText()+msg+ "\r\n");
    }

}

对数据库增多的类,DBAdd扩充了布尔类型再次回到值,调用时方便决断是不是注册成功

对数据库增加的类,DBAdd扩张了布尔类型重临值,调用时有利于判定是或不是注册成功

亚洲必赢官网 ,代码如下:

代码如下:

package com.swift.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.swift.other.User;

public class DBAdd {

    public static boolean add(User user) {

        String phone = user.getUsername();
        String password = user.getPassword();

        Connection conn = DBUtil.getConn();
        PreparedStatement ps=null;
        try {
            ps = conn.prepareStatement("insert into sw_user(username,password) values(?,?)");
            ps.setString(1, phone);
            ps.setString(2, password);
            int count = ps.executeUpdate();
            if (count == 1) {
                return true;
            } 
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeAll(conn, ps, null);
        }
        return false;

    }

}
package com.swift.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.swift.other.User;

public class DBAdd {

    public static boolean add(User user) {

        String phone = user.getUsername();
        String password = user.getPassword();

        Connection conn = DBUtil.getConn();
        PreparedStatement ps=null;
        try {
            ps = conn.prepareStatement("insert into sw_user(username,password) values(?,?)");
            ps.setString(1, phone);
            ps.setString(2, password);
            int count = ps.executeUpdate();
            if (count == 1) {
                return true;
            } 
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeAll(conn, ps, null);
        }
        return false;

    }

}

DBLogin,登录的数据库未有改造

DBLogin,登入的数据库未有改换

代码如下:

代码如下:

package com.swift.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.swift.other.User;

public class DBLogin {

    public static boolean login(User user) {

        Connection conn=DBUtil.getConn();
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            ps=conn.prepareStatement("select * from sw_user where username=? and password=?");
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            rs=ps.executeQuery();
            if(rs.next()) {
                return true;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        DBUtil.closeAll(conn, ps, rs);
        return false;
    }
}
package com.swift.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.swift.other.User;

public class DBLogin {

    public static boolean login(User user) {

        Connection conn=DBUtil.getConn();
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            ps=conn.prepareStatement("select * from sw_user where username=? and password=?");
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            rs=ps.executeQuery();
            if(rs.next()) {
                return true;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        DBUtil.closeAll(conn, ps, rs);
        return false;
    }
}

一而再数据库的工具类DBUtil未有改换

总是数据库的工具类DBUtil未有改观

代码如下:

代码如下:

package com.swift.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {

    public static Connection getConn() {
        Connection conn=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            String url="jdbc:mysql://localhost:3306/sw_database";
            String user="root";
            String password="root";
            conn=DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void closeAll(Connection conn,PreparedStatement ps,ResultSet rs) {

        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(ps!=null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
package com.swift.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {

    public static Connection getConn() {
        Connection conn=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            String url="jdbc:mysql://localhost:3306/sw_database";
            String user="root";
            String password="root";
            conn=DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void closeAll(Connection conn,PreparedStatement ps,ResultSet rs) {

        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(ps!=null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

User类未有变动

User类未有改换

package com.swift.other;

public class User {

    private int id;
    private String username;
    private String password;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public User(int id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }
    public User() {
        super();
    }
    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
    }

}
package com.swift.other;

public class User {

    private int id;
    private String username;
    private String password;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public User(int id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }
    public User() {
        super();
    }
    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
    }

}

居中的工具类Center未有改观

居中的工具类Center未有变动

package com.swift.util;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;

public class Center {
    public static Point getPoint(int width,int height) {
        Toolkit toolkit=Toolkit.getDefaultToolkit();//应该是单例
        int screenW=toolkit.getScreenSize().width;
        int screenH=toolkit.getScreenSize().height;
        int x=(screenW-width)/2;
        int y=(screenH-height)/2;
        Point p=new Point(x,y);
        return p;
    }
    //函数的重载,参数是包装类尺寸——Dimension
    public static Point getPoint(Dimension d) {
        Point p=getPoint(d.width,d.height);
        return p;
    }
}
package com.swift.util;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;

public class Center {
    public static Point getPoint(int width,int height) {
        Toolkit toolkit=Toolkit.getDefaultToolkit();//应该是单例
        int screenW=toolkit.getScreenSize().width;
        int screenH=toolkit.getScreenSize().height;
        int x=(screenW-width)/2;
        int y=(screenH-height)/2;
        Point p=new Point(x,y);
        return p;
    }
    //函数的重载,参数是包装类尺寸——Dimension
    public static Point getPoint(Dimension d) {
        Point p=getPoint(d.width,d.height);
        return p;
    }
}

 

 

Gson包下载地址

Gson包下载地址

 链接: 密码: x88h

 链接: 密码: x88h

网站地图xml地图