主聊天方
package comkingChar;
import javaawtBorderLayout;
import javaawtFrame;
import javaawtTextArea;
import javaawtTextField;
import javaawteventActionEvent;
import javaawteventActionListener;
import javaawteventKeyAdapter;
import javaawteventKeyEvent;
import javaawteventWindowAdapter;
import javaawteventWindowEvent;
import javaioDataOutputStream;
import javaioIOException;
import javanetSocket;
import javanetUnknownHostException;
public class MainChat extends Frame {
TextField tf = new TextField();
TextArea ta = new TextArea();
//为了方便在没连接是时候可以拿到这个socket 设置为成员变量
Socket s=null;
DataOutputStream dos=null;
public void chatLaunch() {
thissetLocation(500, 300);
thissetSize(500, 300);
thissetVisible(true);
thissetResizable(false);
thisadd(tf, BorderLayoutSOUTH);
thisadd(ta, BorderLayoutNORTH);
pack();
thisaddWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
disconnect();
Systemexit(0);
}
});
tfaddActionListener(new myActionListener());
// new myListener()是监听对象 就是keyLISTENER 就是KeyAdapter 就是myListener
thisaddKeyListener(new myListener());
//调用连接服务器
connectServlet();
}
// KeyAdapter实现了keyLISTENER接口
private class myListener extends KeyAdapter {
// 重写需要的方法
public void keyPressed(KeyEvent e) {
int key = egetKeyCode();
switch (key) {
case KeyEventVK_ENTER:
tasetText("i am qiang");
break;
}
}
}
private class myActionListener implements ActionListener {
// 就只有一个方法void actionPerformed(ActionEvent e) 发生 *** 作时调用。
public void actionPerformed(ActionEvent e) {
// trim()去掉空格
String str = tfgetText()trim();
tasetText(str);
tfsetText("");
try {
// InputStreamgetInputStream() 返回此套接字的输入流。 把str的数据流写到socket里 然后连接 服务器就可以取得数据流
doswriteUTF(str);
dosflush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1printStackTrace();
}
}
}
public void connectServlet() {
try {
s = new Socket("localhost", 8888);
dos=new DataOutputStream(sgetOutputStream());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
eprintStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
eprintStackTrace();
}
}
public void disconnect(){
try {
dosclose();
sclose();
} catch (IOException e) {
// TODO Auto-generated catch block
eprintStackTrace();
}
}
public static void main(String[] args) {
new MainChat()chatLaunch();
}
}
服务方:
package comkingChar;
import javaioDataInputStream;
import javaioDataOutputStream;
import javaioIOException;
import javanetServerSocket;
import javanetSocket;
public class ChatServer {
public static void main(String[] args) {
boolean statred = false;
try {
ServerSocket ss = new ServerSocket(8888);
statred = true;
while (statred) {
boolean bConnection = false;
Socket s = ssaccept();
bConnection = true;
DataInputStream dis = new DataInputStream(sgetInputStream());
while (bConnection) {
//readUTF()会阻塞 一直等待接收数据 使用线程解决
String str = disreadUTF();
}
disclose();
}
} catch (IOException e) {
// TODO Auto-generated catch block
eprintStackTrace();
}
}
//不用为类服务 写内部类即可
class myThread implements Runnable{
//每个客户端有自己的相关信心
private Socket s;
private DataInputStream dis=null;
public void run(){
}
}
}
package comkumimhrservertest;
import javanet;
import javanio;
import javaniochannels;
import javaniocharset;
import javaawt;
import javaawtevent;
public class ChatClient {
private SocketChannel sc = null;
private String name = null;
private Frame f;
private TextArea ta;
private TextField tf;
private boolean runnable = true;
public static void main(String[] args){
ChatClient cc = new ChatClient();
cccreateUI();
ccinputName();
ccconnect();
new ReceiveThread(cc,ccgetTextArea())start();
}
public SocketChannel getSc(){
return sc;
}
public void setName(String name){
thisname = name;
}
public TextArea getTextArea(){
return ta;
}
public TextField getTextField(){
return tf;
}
public boolean getRunnable(){
return runnable;
}
public void stop(){
runnable = false;
}
public void shutDown(){
try{
scwrite(ByteBufferwrap("bye"getBytes("UTF-8")));
taappend("Exit in 5 seconds!");
thisstop();
Threadsleep(5000);
scclose();
}catch(Exception e){
eprintStackTrace();
}
Systemexit(0);
}
public void createUI(){
f = new Frame("Client");
ta = new TextArea();
tasetEditable(false);
tf = new TextField();
Button send = new Button("Send");
Panel p = new Panel();
psetLayout(new BorderLayout());
padd(tf,"Center");
padd(send,"East");
fadd(ta,"Center");
fadd(p,"South");
MyClientListener listener = new MyClientListener(this);
sendaddActionListener(listener);
tfaddActionListener(listener);
faddWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
ChatClientthisshutDown();
}
});
fsetSize(400,400);
fsetLocation(600,0);
fsetVisible(true);
tfrequestFocus();
}
public boolean connect(){
try{
sc = SocketChannelopen();
//"zlg"为目标计算机名
InetSocketAddress isa = new InetSocketAddress("192168143",8814);
scconnect(isa);
scconfigureBlocking(false);
scwrite(ByteBufferwrap(namegetBytes("UTF-8")));
}catch(Exception e){
eprintStackTrace();
}
return true;
}
public void inputName(){
String name = javaxswingJOptionPaneshowInputDialog("Input Your Name:");
thissetName(name);
fsetTitle(name);
}
}
class MyClientListener implements ActionListener{
private ChatClient client;
public MyClientListener(ChatClient client){
thisclient = client;
}
public void actionPerformed(ActionEvent e){
TextField tf = clientgetTextField();
String info = tfgetText();
if(infoequals("bye")){
clientshutDown();
}else{
try{
clientgetSc()write(ByteBufferwrap(infogetBytes("UTF-8")));
}catch (Exception e1) {
e1printStackTrace();
}
}
tfsetText("");
tfrequestFocus();
}
}
class ReceiveThread extends Thread{
private ChatClient client;
private TextArea ta;
public ReceiveThread(ChatClient client,TextArea ta){
thisclient = client;
thista = ta;
}
public void run(){
SocketChannel sc = clientgetSc();
ByteBuffer byteBuffer = ByteBufferallocate(2048);
CharBuffer charBuffer = null;
Charset charset = CharsetforName("UTF-8");
CharsetDecoder decoder = charsetnewDecoder();
String msg = null;
int n = 0;
try{
while(clientgetRunnable()){
n = scread(byteBuffer);
if(n>0){
byteBufferflip();
charBuffer = decoderdecode(byteBuffer);
msg = charBuffertoString();
taappend(msg + "\n");
}
byteBufferclear();
Threadsleep(500);
}
}catch(Exception e){
eprintStackTrace();
Systemexit(0);
}
}
}
import javaio;
import javanio;
import javaniochannels;
import javaniocharset;
import javanet;
import javautil;
public class ICQServer {
private Selector selector = null;
private ServerSocketChannel ssc = null;
//服务器端通信端口号
private int port = 8814;
//在线用户列表
private Hashtable<String, SocketChannel> userList = null;
public ICQServer() {}
public ICQServer(int port) {
thisport = port;
}
//初始化服务器
public void init() {
try {
//创建选择器对象
selector = Selectoropen();
//创建ServerSocketChannel
ssc = ServerSocketChannelopen();
//设置ServerSocketChannel为非阻塞模式
sscconfigureBlocking(false);
InetAddress ip = InetAddressgetLocalHost();
Systemoutprintln("主机地址 --------> " + ip);
InetSocketAddress isa = new InetSocketAddress(ip, port);
//将与本通道相关的服务器套接字对象绑定到指定地址和端口
sscsocket()bind(isa);
//创建在线用户列表
userList = new Hashtable<String, SocketChannel> ();
}
catch (IOException e) {
Systemoutprintln("初始化服务器时异常,原因 --------> " + egetMessage());
}
}
//启动服务器
public void start() {
try {
//将ServerSocketChannel注册到Selector上,准备接收新连接请求
SelectionKey acceptKey = sscregister(selector, SelectionKeyOP_ACCEPT);
SocketChannel sc;
int n;
String name; //用户名
String msg; //用户发言信息
while (true) {
//选择当前所有处于就绪状态的通道所对应的选择键,并将这些键组成已选择键集
n = selectorselect(); //n为已选择键集中键的个数
if (n > 0) {
//获取此选择器的已选择键集。
Set readyKeys = selectorselectedKeys();
Iterator it = readyKeysiterator();
//遍历当前已选择键集
while (ithasNext()) {
SelectionKey key = (SelectionKey) itnext();
//从当前已选择键集中移除当前键,避免重复处理
itremove();
//如果当前键对应的通道已准备好接受新的套接字连接
if (keyisAcceptable()) {
//获取当前键对应的可选择通道(ServerSocketChannel)
ssc = (ServerSocketChannel) keychannel();
//接收新的套接字连接请求,返回新建的SocketChannel
sc = (SocketChannel) sscaccept();
//如果有新用户接入
if (sc != null) {
//接收新上线用户姓名
name = readMessage(sc);
//设置新建的SocketChannel为非阻塞模式
scconfigureBlocking(false);
//将新建的SocketChannel注册到Selector上,准备进行数据"写" *** 作,
//并将当前用户名以附件的方式附带记录到新建的选择键上。
SelectionKey newKey = scregister(selector,
SelectionKeyOP_WRITE, name);
//将新上线用户信息加入到在线用户列表
userListput(name, sc);
//发送"新用户上线"通知
transmitMessage(name + " in!", "--Server Info--");
}
}
//否则,如果当前键对应的通道已准备好进行"写" *** 作
else if (keyisWritable()) {
//获取当前键对应的可选择通道(SocketChannel)
sc = (SocketChannel) keychannel();
//接收该通道相应用户的发言信息
msg = readMessage(sc);
//获取选择键上附带记录的当前用户名
name = keyattachment()toString();
//如果用户提出要下线
if (msgequals("bye")) {
//从在线用户列表中移除当前用户
userListremove(name);
//注销当前选择键对应的注册关系
keycancel();
//关闭当前可选择通道
scclose();
//发送"用户下线"通知
transmitMessage(name + " out!", "--Server Info--");
}
//否则,如果接收到的用户发言信息非空("")
else if (msglength() > 0) {
//转发用户发言信息
transmitMessage(msg, name);
}
}
}
}
//延时循环,降低服务器端处理负荷
Threadsleep(500);
}
}
catch (Exception e) {
Systemoutprintln("启动服务器时异常,原因 --------> " + egetMessage());
}
}
//转发用户发言信息
public void transmitMessage(String msg, String name) {
try {
ByteBuffer buffer = ByteBufferwrap( (name + ":" + msg)getBytes("UTF-8"));
//将字节数组包装到缓冲区中
Collection channels = userListvalues();
SocketChannel sc;
for (Object o : channels) {
sc = (SocketChannel) o;
scwrite(buffer);
//将缓冲区数据写入聊天面板(TextArea)
bufferflip();
//将缓冲区ByteBuffer的极限值设置为当前数据实际大小,将缓冲区的值设置为0
}
}
catch (Exception e) {
Systemoutprintln("转发用户发言信息时异常,原因 --------> " + egetMessage());
}
}
//接收用户发言信息
public String readMessage(SocketChannel sc) {
String result = null;
int n = 0;
ByteBuffer buf = ByteBufferallocate(1024);
try {
n = scread(buf);
bufflip();
Charset charset = CharsetforName("UTF-8");
CharsetDecoder decoder = charsetnewDecoder();
CharBuffer charBuffer = decoderdecode(buf);
result = charBuffertoString();
}
catch (IOException e) {
Systemoutprintln("接收用户发言信息时异常,原因 --------> " + egetMessage());
}
return result;
}
public static void main(String args[]) {
ICQServer server = new ICQServer();
serverinit();
serverstart();
}
}
服务端 用户名 y 密码 1 客户端代码在我的评论里,这敲不了那么多字,没办法。
登陆实现类:class Login
package comserver;
import javaawtColor;
import javaawtFont;
import javaawteventActionEvent;
import javaawteventActionListener;
import javaawteventWindowAdapter;
import javaawteventWindowEvent;
import javaxswingJButton;
import javaxswingJFrame;
import javaxswingJLabel;
import javaxswingJPasswordField;
import javaxswingJTextField;
public class Login {
boolean f=false;//按登录时设置的一个标志
private JFrame frame = new JFrame("Welcome To MLDN") ;
//设置窗体
private JButton submit = new JButton("登陆");//设置登录按钮
private JButton reset = new JButton("重置");//设置重置按钮
private JLabel nameLab = new JLabel("服务器:") ;//标签实例化
private JLabel passLab = new JLabel("密 码:"); //标签实例化
private JLabel infoLab = new JLabel("服务器登陆系统"); //标签实例化
private JTextField nameText = new JTextField(10);//单行文本输入条
private JPasswordField passText = new JPasswordField() ;//单行密码文本输入条
public Login(){//登录窗口构造方法
Font fnt = new Font("Serief",FontITALIC + FontBOLD,12); //设置字体
infoLabsetFont(fnt) ; // 设置标签的显示文字
submitaddActionListener(new ActionListener(){ //采用内部匿名类
public void actionPerformed(ActionEvent e){
if(egetSource()==submit){ //判断触发器源是否是提交按钮
String tname = nameTextgetText() ; //得到输入的用户名
String tpass = new String(passTextgetPassword()) ;//得到输入的密码,此时通过getPassageword()方法返回的是字符数组
LoginCheck log = new LoginCheck(tname,tpass) ;//实例化LoginCheck对象,传入输入的用户名和密码
if(logvalidate()){//对用户名和密码进行验证
try{ //线程异常处理try
Threadsleep(2000); //2秒后打开聊天窗口
f=true; //登录成功后的表示项为true
framedispose(); //关闭本窗口
}catch(Exception e1){//异常获取
e1printStackTrace();
}
}else{
infoLabsetText("登陆失败,错误的用户名或密码!") ;//登录失败
}
}
}
});
resetaddActionListener(new ActionListener(){ //采用内部匿名类
public void actionPerformed(ActionEvent e){
if(egetSource()==reset){ //判断触发器源是否是提交按钮
nameTextsetText(""); //设置文本框中的内容
passTextsetText(""); //设置文本框中的内容
infoLabsetText("服务器登陆系统"); //恢复标签显示
}
}
});
frameaddWindowListener(new WindowAdapter(){//加入窗口监听
public void windowClosing(WindowEvent e){ }
}); // 加入事件
framesetLayout(null); //使用绝对定位
nameLabsetBounds(5,5,60,20); //设置标签的位置及大小
passLabsetBounds(5,30,60,20); //设置标签的位置及大小
infoLabsetBounds(5,65,220,30); //设置标签的位置及大小
nameTextsetBounds(65,5,100,20); //设置文本域的位置及大小
passTextsetBounds(65,30,100,20); //设置密码域的位置及大小
submitsetBounds(165,5,60,20); //设置按钮的位置及大小
resetsetBounds(165,30,60,20); //设置按钮的位置及大小
frameadd(nameLab); //向窗体加入标签
frameadd(passLab); //向窗体加入标签
frameadd(infoLab); //向窗体加入标签
frameadd(nameText); //向窗体加入文本框
frameadd(passText); //向窗体加入密码框
frameadd(submit); //向窗体加入按钮
frameadd(reset) ;//向窗体加入按钮
framesetSize(280,130); //设置窗体大小
framegetContentPane()setBackground(Colorgreen) ;//设置窗体的背景颜色
framesetLocation(300,200) ;//设置窗体在电脑桌面上的位置
framesetVisible(true); //显示窗口
while(f==false){ //当登录失败时,一直循环运行,
}
new MyServer();//显示窗体页面
}
}
验证登陆实现类 class LoginCheck
package comserver;
public class LoginCheck {
private String name ;//用户名
private String password ;//密码
//构造方法
public LoginCheck(String name,String password){
thisname = name ;//传递用户名
thispassword = password ;//传递密码
}
//验证用户名和密码
public boolean validate(){
//验证方法
if("y"equals(name)&&"1"equals(password)){ //判断用户名和密码是否正确
return true; //返回true
}else{
return false ;//返回false
}
}
}
package comserver;
import javaawt;
import javaawteventActionEvent;
import javaawteventActionListener;
import javaioBufferedReader;
import javaioInputStreamReader;
import javaioPrintWriter;
import javanetServerSocket;
import javanetSocket;
import javatextDateFormat;
import javautilDate;
import javaxswing;
聊天实现类 class MyServer
public class MyServer {
protected JLabel lab10;
// 全体变量,做传递的一个组件
String s = "已经成功连接";
// 初始字符串,在两个聊天窗口链接成功时输出,同时作为两个窗口传递字符的一个变量
// 构造方法
public MyServer(){
try{//异常处理
JFrame frame=new JFrame("服务器窗口");
//设置窗体
framesetLayout(null);
//让布局管理器为空,使用绝对定位
Font fnt=new Font("Serief",FontPLAIN,40);//字体设置
Font fnt1=new Font("Serief",FontPLAIN,20);//字体设置
//我的用户名显示
JLabel lab1=new JLabel("服务器名:",JLabelLEFT);
//标签实例化,文本左对齐
lab1setBounds(8, 10, 100, 20);
//设置组件位置及大小
frameadd(lab1);
//添加组件
JTextField text2=new JTextField(30); //单行文本输入组件
text2setBounds(150, 10, 200, 20);//设置组件位置及大小
text2setEnabled(false);//文本条不可编辑
text2setText("笑笑聊天室");//输入内容
text2setFont(fnt1);//设置字体
frameadd(text2);//添加组件
//服务器IP显示
JLabel lab2=new JLabel("当前服务器IP:",JLabelLEFT);
//标签实例化,文本左对齐
lab2setBounds(8, 45, 100, 20);//设置组件位置及大小
frameadd(lab2);//添加组件
JTextField text3=new JTextField(30);//单行文本输入组件
text3setBounds(150, 45, 200, 20);//设置组件位置及大小
text3setEnabled(false);
//文本不可编辑
text3setText("127001");//输入内容
text3setFont(fnt1);//设置字体
frameadd(text3);
//添加组件
//服务器端口显示
JLabel lab3=new JLabel("当前服务器端口:",JLabelLEFT);
//标签实例化,文本左对齐
lab3setBounds(8, 80, 100, 20);//设置组件位置及大小
frameadd(lab3);//添加组件
JTextField text4=new JTextField(30);//单行文本输入组件
text4setBounds(150, 80, 200, 20);//设置组件位置及大小
text4setEnabled(false);//文本不可编辑
text4setText("8888");//输入内容
text4setFont(fnt1);//设置字体
frameadd(text4);//添加组件
//聊天记录显示
JLabel lab4=new JLabel("聊天记录如下:",JLabelLEFT);
//标签实例化 文本左对齐
lab4setBounds(8, 115, 100, 20);//设置组件位置及大小
frameadd(lab4);//添加组件
final JTextArea text1=new JTextArea();//多行文本输入组件
text1setEnabled(false);//文本不可编辑
text1setLineWrap(true);//自动换行
JScrollPane scr=new JScrollPane(text1,JScrollPaneVERTICAL_SCROLLBAR_ALWAYS,JScrollPaneHORIZONTAL_SCROLLBAR_ALWAYS); //设置滚动条,水平和垂直滚动条始终显示
scrsetBounds(8, 150, 450, 350);//设置组件位置及大小
frameadd(scr);//添加组件
//聊天输入窗口及确定
JLabel lab5=new JLabel("请输入聊天内容:",JLabelLEFT); //标签实例化,文本左对齐
lab5setBounds(8, 500, 100, 20);//设置组件位置及大小
frameadd(lab5);//添加组件
final JTextArea text5=new JTextArea();//多行文本输入组件
text5setLineWrap(true);//自动换行
JScrollPane scr2=new JScrollPane(text5,JScrollPaneVERTICAL_SCROLLBAR_ALWAYS,JScrollPaneHORIZONTAL_SCROLLBAR_ALWAYS);//设置滚动条,水平和垂直滚动条始终显示
scr2setBounds(150, 500, 300, 50);//设置组件位置及大小
frameadd(scr2);//添加组件
final JButton but=new JButton("确定");//设置确定按钮
butsetFont(fnt);//添加字体设置
butsetBounds(480, 500, 200, 50);//设置组件位置及大小
butaddActionListener(
new ActionListener(){ //采用内部匿名类
public void actionPerformed(ActionEvent e){
if(egetSource()==but){ //判断触发器源是否是提交按钮
text1append("笑笑: "+lab10getText()+"\n ");//在聊天记录上添加文本
text1append(text5getText()+"\n"); //将输入的聊天内容输出在聊天记录上
s=text5getText(); //得到聊天内容
text5setText(""); // 将聊天窗口内容设置为空
}
}
});
frameadd(but);//添加组件
//当前时间显示
JLabel lab7=new JLabel("时间显示:",JLabelLEFT);//标签实例化,文本左对齐
lab7setBounds(450, 20, 100, 20);//设置组件位置及大小
frameadd(lab7);//添加组件
DateFormat df=DateFormatgetDateTimeInstance();//取得系统时间
String df2= dfformat(new Date()); //将时间转换成字符串
JLabel lab8=new JLabel(df2,JLabelLEFT);//标签实例化,文本左对齐
lab8setBounds(520, 20, 130, 20);//设置组件位置及大小
frameadd(lab8);//添加组件
lab10=lab8; //传递时间显示,以便能在聊天记录上显示记录时间
new Time(lab8); //使时间动态显示
//用户列表显示
JLabel lab6=new JLabel("用户列表:",JLabelLEFT);//标签实例化,文本左对齐
lab6setBounds(500, 40, 100, 20);//设置组件位置及大小
frameadd(lab6);//添加组件
JTextArea text6=new JTextArea();//标签实例化,文本左对齐
text6setEnabled(false);//文本不可编辑
text6setLineWrap(true);//自动换行
JScrollPane scr3=new JScrollPane(text6,JScrollPaneVERTICAL_SCROLLBAR_ALWAYS,JScrollPaneHORIZONTAL_SCROLLBAR_ALWAYS);//设置滚动条,水平和垂直滚动条始终显示
scr3setBounds(460, 70, 220, 420);//设置组件位置及大小
frameadd(scr3);//添加组件
//窗口的属性
framesetSize(700,600);//窗口大小
framegetContentPane()setBackground(Colorpink);//窗口的背景颜色
framesetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);//关闭窗口时关闭程序
framesetLocation(100,50);//在电脑桌面上出现的位置
framesetVisible(true);//显示窗口
//连个窗口连接
//建立Server Socket并等待连接请求
ServerSocket server =new ServerSocket(8889);
Socket socket=serveraccept();
//连接建立,通过Socket获取连接上的输入/输出流
BufferedReader in=new BufferedReader(new InputStreamReader(socketgetInputStream()));
final PrintWriter out =new PrintWriter(socketgetOutputStream());
//先读取Client发送的数据,然后从标准输入读取数据发送给Client当接收到bye时关闭连接
String s1="",s2="";
//标志字符串,作为传递字符串使用
//得到其他窗口传递的字符串,并判断是否结束
while(!(s1=inreadLine())equals("bye")){
text6setText("可可在线"); //当连接成功是在用户列表中 输出用户名字
if(!s1equals("")){ //如果传递的字符串不为 空
text1append("可可: "+lab10getText()+"\n ");//在聊天记录上添加文本
text1append(s1+"\n"); //将输入的聊天内容输出在聊天记录上
}
s2=s;//将在聊天窗口中得到的字符串传递给输出字符串
for(;s2equals("")||s2equals(null);s2=s){//当传递的字符串为空时等待用户输入聊天内容
}
s="";//将在聊天窗口中得到的字符串设为空
if(!s2equals("")&&!s2equals(null)){// s2不为空时做
outprintln(s2); //向其他窗口输出字符串
}
outflush();//输出聊天内容
}
//关闭连接
inclose();
outclose();
socketclose();
serverclose();
}catch(Exception e){
}
}
//main函数
public static void main(String args[]){
new Login();//登录实现 } }
}
}
时间类 class Time
package comserver;
import javaawteventActionEvent;
import javaawteventActionListener;
import javatextSimpleDateFormat;
import javautilDate;
import javaxswingJLabel;
import javaxswingTimer; //时间类
public class Time {
public Time(JLabel time){
//构造方法 thissetTimer(time);
//设置时间
}
public void setTimer(JLabel time){
//设置时间方法
final JLabel varTime = time;
//传递组件
Timer timeAction = new Timer(1000, new ActionListener() {
//时间监听
public void actionPerformed(ActionEvent e) {
long timemillis = SystemcurrentTimeMillis();//得到系统时间
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//转换日期显示格式
varTimesetText(dfformat(new Date(timemillis)));//输出得到的时间
}
});
timeActionstart(); //开启线程
}
}
<script type="text/javascript" language=JavaScript charset="UTF-8">
documentonkeydown=function(event){
var e = event || windowevent || argumentscalleecallerarguments[0];
if(e && ekeyCode==13){ // enter 键
//发送信息代码
}
};
</script>
enter键的keyCode是13,通过onkeydown可以判断按下enter然后做发送消息。
参考资料:
这个时比较简单的。
package QQ;
import javanet;
import javaio;
import javasql;
import javautil;
public class QQServer {
public static void main(String args[]) {
try {
HashMap<String , Socket> hm = new
HashMap<String , Socket>() ;
// 服务器到8000端口监听(1)
ServerSocket ss = new ServerSocket
(8000);
while (true) {
Systemoutprintln("服务器正在
8000端口监听");
Socket s = ssaccept();
MyService t = new MyService();
tsetSocket(s) ;
tsetHashMap(hm) ;
tstart();
}
} catch (Exception e) {
eprintStackTrace();
}
}
}
class MyService extends Thread {
private Socket s ;
private HashMap<String , Socket> hm ;
public void setHashMap(HashMap<String , Socket> hm){
thishm = hm ;
}
public void setSocket(Socket s){
thiss = s ;
}
public void run() {
try {
// 接收客户端发送来的用户名和密码(2)
InputStream is = sgetInputStream();
InputStreamReader isr = new InputStreamReader
(is);
BufferedReader br = new BufferedReader(isr);
String uandp = brreadLine();
// 拆分用户名和密码(4)
String u = "";
String p = "";
try{
u = uandpsplit("%")[0];
p = uandpsplit("%")[1];
}catch(Exception e){}
// 到数据库中验证(5)
ClassforName
("commicrosoftjdbcsqlserverSQLServerDriver");
Connection cn = DriverManager
getConnection(
"jdbc:microsoft:sqlserver://127001:1433;databasename=qq2",
"sa", "123");
PreparedStatement ps = cn
prepareStatement("select
username from username where username= and password=");
pssetString(1, u);
pssetString(2, p);
ResultSet rs = psexecuteQuery();
// 发送确认信息到客户端(7)
OutputStream os = sgetOutputStream();
OutputStreamWriter osw = new
OutputStreamWriter(os);
PrintWriter pw = new PrintWriter(osw, true);
if (rsnext()) {
pwprintln("ok");
//将自己的名字发送给HashMap中的其他人
(13)
for(Socket ts : hmvalues()){
OutputStream tos =
tsgetOutputStream() ;
OutputStreamWriter tosw = new
OutputStreamWriter(tos) ;
PrintWriter tpw = new
PrintWriter(tosw , true) ;
tpwprintln("user%"+u) ;
}
//将其他人的名字发送给自己(13)
for(String tu : hmkeySet()){
pwprintln("user%"+tu) ;
}
//将用户名和对应的Socket存入HashMap
(13)
hmput(u, s) ;
// 接收客户端发送来的信息(11)
while (true) {
String message = brreadLine
();
if(messageequals("exit")){
for(Socket ts :
hmvalues()){
OutputStream
tos = tsgetOutputStream() ;
OutputStreamWriter tosw = new OutputStreamWriter(tos) ;
PrintWriter
tpw = new PrintWriter(tosw , true) ;
tpwprintln
("exit%"+u);
}
hmremove(u);
}
String to = messagesplit
("%")[0];
String mess = messagesplit
("%")[1];
Socket ts = hmget(to);
OutputStream tos =
tsgetOutputStream();
OutputStreamWriter tosw = new
OutputStreamWriter(tos);
PrintWriter tpw = new
PrintWriter(tosw, true);
tpwprintln("mess%"+mess
+"\n");
Systemoutprintln(message);
}
} else {
pwprintln("err");
}
} catch (Exception e) {}
}
}
呵呵,楼主您好!要用Java做聊天室说简单也不简单,但是说难呢也不难
说简单点,就是会话跟踪技术(我个人这样理解)要做聊天室,您需要
使用到的工具: tomcat 服务器(因为是免费的,其他也可以哦,呵呵)
Myeclipse(sun公司提供的编写Java程序的工具,别说你不知道哈,
哪样的话我就晕倒了哦,呵呵)
页面框架的设计:indexjsp(聊天室主页面)index_topjsp(聊天室的顶部页面)
usersonlinejsp(在线人数的统计及显示页面) sendMessagejsp(发送信息的页面)
showMessagejsp(显示聊天信息的页面)registerjsp(用户注册的页面)
loginjsp(用户登录页面)
当然,这是最简单的设计方式咯您也可以设计得更好点
页面介绍与功能:
indexjsp 主要是聊天室的主页面由上中下3个框架组成,中间部分在分为
左右2个框架实际上indexjsp就是一个由于5个框架组成的页面
顶部框架:放index_topjsp页面可以设计自己聊天室的特色(比如说:logo)
中间部分的左边框架:showMessagejsp 显示聊天的信息
中间部分的右边框架:usersonlinejsp(在线人数的统计及显示页面)
底部框架:sendMessagejsp 这个发送信息的jsp页面不多说吧
聊天室的框架的设计大楷就是这样子咯
实现聊天:
1编写一个servlet,用户处理的信息(包括验证用户是否登录和聊天信息)。
2用户发送信息之后,将发送的信息存放到Application中(群聊)(放在session中就是私聊)
3显示信息的页面每个XX秒中获取session或者Application中的数据显示出来就OK了
更多的东西还是需要您学习Ajax之后再做,会有不一样的效果哦。祝您成功哟呵呵
以上就是关于谁可以帮我做一下用Java编写的聊天程序可以实现发送表情功能啊,,求求求全部的内容,包括:谁可以帮我做一下用Java编写的聊天程序可以实现发送表情功能啊,,求求求、Java简单聊天程序、你好,你有用java编写的聊天室的代码吗,基于c/s架构的等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)