资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

java聊天窗口代码 java聊天程序代码

java 聊天室 源代码

【ClientSocketDemo.java 客户端Java源代码】

成都创新互联公司主要从事做网站、网站制作、网页设计、企业做网站、公司建网站等业务。立足成都服务沅江,十年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:13518219792

import java.net.*;

import java.io.*;

public class ClientSocketDemo

{

//声明客户端Socket对象socket

Socket socket = null;

//声明客户器端数据输入输出流

DataInputStream in;

DataOutputStream out;

//声明字符串数组对象response,用于存储从服务器接收到的信息

String response[];

//执行过程中,没有参数时的构造方法,本地服务器在本地,取默认端口10745

public ClientSocketDemo()

{

try

{

//创建客户端socket,服务器地址取本地,端口号为10745

socket = new Socket("localhost",10745);

//创建客户端数据输入输出流,用于对服务器端发送或接收数据

in = new DataInputStream(socket.getInputStream());

out = new DataOutputStream(socket.getOutputStream());

//获取客户端地址及端口号

String ip = String.valueOf(socket.getLocalAddress());

String port = String.valueOf(socket.getLocalPort());

//向服务器发送数据

out.writeUTF("Hello Server.This connection is from client.");

out.writeUTF(ip);

out.writeUTF(port);

//从服务器接收数据

response = new String[3];

for (int i = 0; i response.length; i++)

{

response[i] = in.readUTF();

System.out.println(response[i]);

}

}

catch(UnknownHostException e){e.printStackTrace();}

catch(IOException e){e.printStackTrace();}

}

//执行过程中,有一个参数时的构造方法,参数指定服务器地址,取默认端口10745

public ClientSocketDemo(String hostname)

{

try

{

//创建客户端socket,hostname参数指定服务器地址,端口号为10745

socket = new Socket(hostname,10745);

in = new DataInputStream(socket.getInputStream());

out = new DataOutputStream(socket.getOutputStream());

String ip = String.valueOf(socket.getLocalAddress());

String port = String.valueOf(socket.getLocalPort());

out.writeUTF("Hello Server.This connection is from client.");

out.writeUTF(ip);

out.writeUTF(port);

response = new String[3];

for (int i = 0; i response.length; i++)

{

response[i] = in.readUTF();

System.out.println(response[i]);

}

}

catch(UnknownHostException e){e.printStackTrace();}

catch(IOException e){e.printStackTrace();}

}

//执行过程中,有两个个参数时的构造方法,第一个参数hostname指定服务器地址

//第一个参数serverPort指定服务器端口号

public ClientSocketDemo(String hostname,String serverPort)

{

try

{

socket = new Socket(hostname,Integer.parseInt(serverPort));

in = new DataInputStream(socket.getInputStream());

out = new DataOutputStream(socket.getOutputStream());

String ip = String.valueOf(socket.getLocalAddress());

String port = String.valueOf(socket.getLocalPort());

out.writeUTF("Hello Server.This connection is from client.");

out.writeUTF(ip);

out.writeUTF(port);

response = new String[3];

for (int i = 0; i response.length; i++)

{

response[i] = in.readUTF();

System.out.println(response[i]);

}

}

catch(UnknownHostException e){e.printStackTrace();}

catch(IOException e){e.printStackTrace();}

}

public static void main(String[] args)

{

String comd[] = args;

if(comd.length == 0)

{

System.out.println("Use localhost(127.0.0.1) and default port");

ClientSocketDemo demo = new ClientSocketDemo();

}

else if(comd.length == 1)

{

System.out.println("Use default port");

ClientSocketDemo demo = new ClientSocketDemo(args[0]);

}

else if(comd.length == 2)

{

System.out.println("Hostname and port are named by user");

ClientSocketDemo demo = new ClientSocketDemo(args[0],args[1]);

}

else System.out.println("ERROR");

}

}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

【ServerSocketDemo.java 服务器端Java源代码】

import java.net.*;

import java.io.*;

public class ServerSocketDemo

{

//声明ServerSocket类对象

ServerSocket serverSocket;

//声明并初始化服务器端监听端口号常量

public static final int PORT = 10745;

//声明服务器端数据输入输出流

DataInputStream in;

DataOutputStream out;

//声明InetAddress类对象ip,用于获取服务器地址及端口号等信息

InetAddress ip = null;

//声明字符串数组对象request,用于存储从客户端发送来的信息

String request[];

public ServerSocketDemo()

{

request = new String[3]; //初始化字符串数组

try

{

//获取本地服务器地址信息

ip = InetAddress.getLocalHost();

//以PORT为服务端口号,创建serverSocket对象以监听该端口上的连接

serverSocket = new ServerSocket(PORT);

//创建Socket类的对象socket,用于保存连接到服务器的客户端socket对象

Socket socket = serverSocket.accept();

System.out.println("This is server:"+String.valueOf(ip)+PORT);

//创建服务器端数据输入输出流,用于对客户端接收或发送数据

in = new DataInputStream(socket.getInputStream());

out = new DataOutputStream(socket.getOutputStream());

//接收客户端发送来的数据信息,并显示

request[0] = in.readUTF();

request[1] = in.readUTF();

request[2] = in.readUTF();

System.out.println("Received messages form client is:");

System.out.println(request[0]);

System.out.println(request[1]);

System.out.println(request[2]);

//向客户端发送数据

out.writeUTF("Hello client!");

out.writeUTF("Your ip is:"+request[1]);

out.writeUTF("Your port is:"+request[2]);

}

catch(IOException e){e.printStackTrace();}

}

public static void main(String[] args)

{

ServerSocketDemo demo = new ServerSocketDemo();

}

}

请问能不能帮我写一个Java的聊天窗口文件源代码,不要很复杂,只要能运行,聊天就行了!我用淘宝金币换,谢

话说网上真的好多啊...

package client;

import java.awt.Color;

import java.awt.Container;

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.Socket;

import java.util.Date;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

import javax.swing.JTextField;

public class ClientFrame extends JFrame{

private JTextArea allmsg;

private JTextField welcome,copyright,chatmsg;

private JButton send;

private JScrollPane js;

private boolean isConnected = true;

public DataOutputStream out;

public DataInputStream in;

public Socket s = null;

String nic; /* -- 保存用户昵称 --*/

/**

* 初始化客户端资源

* 1.获取从LoginFrame传递过来的参数

* 2.初始化界面元素

* 3.初始化通信所需要的资源 EG:输入/输出流(DataInputStream/DataOutputStream)

* */

public ClientFrame(String name,Socket socket)

{

this.setSize(310,660);

this.setLocation(290,50);

this.setTitle("聊天室客户端"+name+"");/* -- 指定窗口的标题 --*/

this.s = socket;/* -- 接收从LoginFrame中传递过来的Socket --*/

this.nic = name+" 说: ";

welcome = new JTextField(" "+name+" 欢迎您来到聊天室 ",100);

welcome.setBackground(Color.blue);

welcome.setEnabled(false);

copyright = new JTextField(" ----- all copyright @ TOP-king -----");

copyright.setEnabled(false);

allmsg = new JTextArea();

allmsg.setEditable(false);

allmsg.append(" 系统消息: 欢迎登录在线聊天室 \n");

js = new JScrollPane(allmsg);//为JTextArea添加滚动条

chatmsg = new JTextField("在此输入聊天信息");

chatmsg.addActionListener(new listen());

send = new JButton("发送");

send.addActionListener(new listen());/* -- 添加事件监听器 --*/

try {

out = new DataOutputStream(s.getOutputStream());

in = new DataInputStream(s.getInputStream());

} catch (IOException e) {JOptionPane.showMessageDialog(null, "系统异常","错误",JOptionPane.OK_CANCEL_OPTION);}

addcomponettocontainer();

/* -- 当用户关闭窗口时进行相关的处理 eg:Socket Data(Input/Output)Stream 的关闭--*/

this.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent we)

{

sendmsg("quitlogout");/* -- 向服务器端发送关闭信息 --*/

isConnected = false;

destory();/* -- 销毁窗口资源 --*/

}

});

new Thread(new linread()).start();/* -- 启动读取信息线程 --*/

}

public void addcomponettocontainer()

{

Container c = this.getContentPane();

c.setLayout(null);

welcome.setBounds(75,10,150,20);

js.setBounds(10,50,280,500);

chatmsg.setBounds(10,560,180,30);

send.setBounds(220,560,70,30);

copyright.setBounds(10,600,280,20);

c.add(welcome);

c.add(js);

c.add(chatmsg);

c.add(send);

c.add(copyright);

this.setVisible(true);

this.setResizable(false);

}

class listen implements ActionListener

{

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

if(e.getSource()==send||e.getSource()==chatmsg)

{

String msg = chatmsg.getText().trim();

if("".equals(msg))

{

JOptionPane.showMessageDialog(null,"发送信息不能为空!","错误",JOptionPane.OK_OPTION);

}

else

{sendmsg((new Date()).toLocaleString()+"\n"+nic+msg+"\n");chatmsg.setText("");}

}

}

}

/* -- 向服务器端发送信息 --*/

public void sendmsg(String m)

{

if(isConnected)//如果socket的输出流没关闭

{

try {

out.writeUTF(m);

} catch (IOException e) {

JOptionPane.showMessageDialog(null,"发送信息失败!(系统异常)","错误",JOptionPane.OK_OPTION);

}

}

else

{

JOptionPane.showMessageDialog(null,"发送信息失败!(服务器关闭/网络故障)","错误",JOptionPane.OK_OPTION);

}

}

/* -- 读取信息线程 --*/

class linread implements Runnable

{

public void run()

{

read();

}

public void read()

{

while(isConnected)

{

try {

String msg = in.readUTF();

if("SYSTEM_CLOSED".equals(msg))

{

JOptionPane.showMessageDialog(null,"读取消息失败(服务器关闭/网络故障)!","错误",JOptionPane.OK_OPTION);

isConnected = false;

}

else

allmsg.append(msg+"\n");

} catch (IOException e) {

}

}//end while

JOptionPane.showMessageDialog(null,"读取消息失败(服务器关闭/网络故障)!","错误",JOptionPane.OK_OPTION);

}//end read()

}

public void destory()

{

try {

this.out.close();

this.in.close();

this.s.close();

} catch (IOException e) {

}

this.dispose();

}

}

======================================================

package client;

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

import java.io.*;

import java.net.*;

public class LoginFrame extends JFrame{

private JTextField name;

private JTextField ip;

private JButton ok,cancle;

public Socket socket;

public LoginFrame()

{

super("登录框");

this.setSize(400,80);

this.setLocation(100,100);

name = new JTextField("昵称");

ip = new JTextField("127.0.0.1");

ok = new JButton("登录");

cancle = new JButton("取消");

ok.addActionListener(new listenEvent());

cancle.addActionListener(new listenEvent());

//建立容器

addcomponettocontainer();

this.setDefaultCloseOperation(EXIT_ON_CLOSE);

}

/**

* 建立容器及控件

*/

public void addcomponettocontainer()

{

Container c = this.getContentPane();

c.setLayout(null);

name.setBounds(10,10,100,30);

ip.setBounds(120,10,100,30);

ok.setBounds(230,10,70,30);

cancle.setBounds(310,10,70,30);

c.add(name);

c.add(ip);

c.add(ok);

c.add(cancle);

this.setVisible(true);

this.setResizable(false);

}

public class listenEvent implements ActionListener

{

public void actionPerformed(ActionEvent event) {

// TODO Auto-generated method stub

if(event.getSource()==ok)

{

String n = name.getText().trim();

String i = ip.getText().trim();

if("".equals(n)||"".equals(i))

{

JOptionPane.showMessageDialog(null,"昵称、IP不能够为空!","错误",JOptionPane.OK_OPTION);

}

else{login(n,i);}

}

if(event.getSource()==cancle)

{

name.setText("");

ip.setText("");

}

}

}

/**

* 进行登录

* @param name

* @param ip

*/

public void login(String name,String ip)

{

try {

socket = new Socket(ip,7777);

DataOutputStream out = new DataOutputStream(socket.getOutputStream());

out.writeUTF(name);

out.flush();//强制输出缓存中的内容

//out.close();

new ClientFrame(name,socket);

destroywindow();

} catch (UnknownHostException e) {

JOptionPane.showMessageDialog(null,"找不到主机地址(IP错误/网络故障)!","错误",JOptionPane.OK_OPTION);

} catch (IOException e) {

}

}

public void destroywindow()

{

this.dispose();

}

public static void main(String[] args)

{

new LoginFrame();

}

}

==================================================

package server;

import java.awt.Container;

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.ServerSocket;

import java.net.Socket;

import java.util.ArrayList;

import java.util.Date;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

import javax.swing.JTextField;

public class ServerFrame extends JFrame{

/**

*

*/

private static final long serialVersionUID = 1L;

private JTextArea allmsg;

private JTextField currnum,totalnum,copyright,chatmsg;

private JButton send;

private JScrollPane js;

int num1,num2,port;/* -- num1:当前在线人数 num2:总上线人数 port:服务端口号 --*/

private ServerSocket ss;

ArrayListuser lists;//存放所有在线用户

public ServerFrame()

{

super("聊天室服务器端");

this.setSize(310,660);

this.setLocation(200,50);

lists = new ArrayListuser();

num1 = num2 =0;

port = 7777;

currnum = new JTextField(" 当前在线人数: "+num1);

currnum.setEnabled(false);

totalnum = new JTextField(" 上线总人数: "+num2);

totalnum.setEnabled(false);

copyright = new JTextField(" ----- all copyright @ TOP-king -----");

copyright.setEnabled(false);

allmsg = new JTextArea();

allmsg.append(" --------------- 系统消息 --------------\n");

allmsg.setEditable(false);

allmsg.setLineWrap(true); //允许自动换行

js = new JScrollPane(allmsg);//为JTextArea添加滚动条

chatmsg = new JTextField("在此输入系统信息");

chatmsg.addActionListener(new ActionListener(){

@SuppressWarnings("deprecation")

public void actionPerformed(ActionEvent arg0) {

String str = chatmsg.getText().trim();

if(!"".equals(str))

{sendmsg((new Date()).toLocaleString()+" -- 系统消息: "+str);chatmsg.setText("");}

else

JOptionPane.showMessageDialog(null, "消息不能为空","错误",JOptionPane.OK_OPTION);

chatmsg.setText("");/* -- 发送信息后,将输入栏中的信息清空 -- */

}

});

send = new JButton("发送");

send.addActionListener(new ActionListener(){

@SuppressWarnings("deprecation")

public void actionPerformed(ActionEvent arg0) {

String str = chatmsg.getText().trim();

if(!"".equals(str))

{sendmsg((new Date()).toLocaleString()+" -- 系统消息: "+str);chatmsg.setText("");}

else

JOptionPane.showMessageDialog(null, "消息不能为空","错误",JOptionPane.OK_OPTION);

chatmsg.setText("");/* -- 发送信息后,将输入栏中的信息清空 -- */

}

});

//建立容器

addcomponettocontainer();

this.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent we)

{

sendmsg("SYSTEM_CLOSED");/* -- 向客户端发送服务器关闭信息 -- */

destory();

}

});

start(); /* -- 启动连接服务 -- */

}

public void addcomponettocontainer()

{

//Container建立容器

Container c = this.getContentPane();

c.setLayout(null);

currnum.setBounds(20,15,130,20);

totalnum.setBounds(155,15,125,20);

js.setBounds(10,50,280,500);

chatmsg.setBounds(10,560,180,30);

send.setBounds(220,560,70,30);

copyright.setBounds(10,600,280,20);

c.add(currnum);

c.add(totalnum);

c.add(js);

c.add(chatmsg);

c.add(send);

c.add(copyright);

this.setVisible(true);

this.setResizable(false);

}

/**

* start()方法监听客户的连接

* 并且保存客户端的相关信息EG:用户昵称、用户所使用的Socket

* 用户连接到服务器成功之后,将其保存到用户列表中,并为该用户启动一个线程用于通信 */

@SuppressWarnings("deprecation")

public void start()

{

boolean isStarted = false;/* -- 用于标记服务器是否已经正常启动 -- */

try {

this.ss = new ServerSocket(port);

isStarted = true;

this.allmsg.append((new Date()).toLocaleString()+" 服务器启动 @ 端口: "+port+"\n");

while(isStarted)

{

Socket client = this.ss.accept(); /* -- 监听客户端的连接 -- */

DataInputStream in = new DataInputStream(client.getInputStream());

String name = in.readUTF();

user u = new user();

u.name = name;

u.socket = client;

lists.add(u); //将该用户加到列表中去

num1++;

num2++;

currnum.setText(" 当前在线人数: "+num1);

totalnum.setText(" 上线总人数: "+num2);

this.allmsg.append((new Date()).toLocaleString()+" : "+u.name+" 登录 \n");

new Thread(new ClientThread(u)).start();/* -- 为该用户启动一个通信线程 -- */

}

} catch (IOException e) {

System.out.println("服务器已经启动......");

System.exit(0);

}

}

/**

* 通信线程主要功能包括:

* 1.监听客户端输入的信息

* 2.将接收到的信息转发给其他用户 */

class ClientThread implements Runnable

{

user user = null;

boolean isConnected = true;

DataInputStream dis = null;

DataOutputStream dos = null;

public ClientThread(user u)

{

this.user = u;

try {

this.dis = new DataInputStream(this.user.socket.getInputStream());

this.dos = new DataOutputStream(this.user.socket.getOutputStream());

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public void run()

{

readmsg();

}

/* -- 读取客户的聊天信息 -- */

@SuppressWarnings("deprecation")

public void readmsg()

{

while(isConnected)

{

try {

String msg = dis.readUTF();

if("quitlogout".equals(msg))//当用户关闭客户端窗口时,发送quit字符串 表示用户已经退出

{

num1--;

try{

this.dis.close();

this.dos.close();

this.user.socket.close();

this.isConnected = false;

}catch(IOException ioe)

{

ioe.printStackTrace();

}finally{

this.isConnected = false;

if(dis!=null) this.dis.close();

if(dos!=null) this.dos.close();

if(this.user.socket!=null) this.user.socket.close();

}

lists.remove(this.user);//从列表中删除该用户

currnum.setText(" 当前在线人数: "+num1);

allmsg.append((new Date()).toLocaleString()+" : "+this.user.name+" 退出\n");

}

else

sendmsg(msg);

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

/* -- 将信息进行转发 -- */

public void sendmsg(String msg)

{

user us = new user();

DataOutputStream os = null;

if(lists.size()0)

{

for(int i=0;ilists.size();i++)

{

us = lists.get(i);

try {

os = new DataOutputStream(us.socket.getOutputStream());

os.writeUTF(msg);

} catch (IOException e) {

e.printStackTrace();

}

}

}

else

JOptionPane.showMessageDialog(null, "当前无用户在线。发送消息失败","失败",JOptionPane.OK_OPTION);

}

public void destory()

{

try {

this.ss.close();

} catch (IOException e) {

e.printStackTrace();

}

this.dispose();

}

public static void main(String[] args)

{

new ServerFrame();

}

}

=================================================

package server;

import java.net.*;

public class user {

String name;

Socket socket;

}

你好,你有用java编写的聊天室的代码吗,基于c/s架构的

服务端 用户名 y 密码 1 客户端代码在我的评论里,这敲不了那么多字,没办法。

登陆实现类:class Login

package com.server;

import java.awt.Color;

import java.awt.Font;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPasswordField;

import javax.swing.JTextField;

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",Font.ITALIC + Font.BOLD,12); //设置字体

infoLab.setFont(fnt) ; // 设置标签的显示文字

submit.addActionListener(new ActionListener(){ //采用内部匿名类

public void actionPerformed(ActionEvent e){

if(e.getSource()==submit){ //判断触发器源是否是提交按钮

String tname = nameText.getText() ; //得到输入的用户名

String tpass = new String(passText.getPassword()) ;//得到输入的密码,此时通过getPassageword()方法返回的是字符数组

LoginCheck log = new LoginCheck(tname,tpass) ;//实例化LoginCheck对象,传入输入的用户名和密码

if(log.validate()){//对用户名和密码进行验证

try{ //线程异常处理try

Thread.sleep(2000); //2秒后打开聊天窗口

f=true; //登录成功后的表示项为true

frame.dispose(); //关闭本窗口

}catch(Exception e1){//异常获取

e1.printStackTrace();

}

}else{

infoLab.setText("登陆失败,错误的用户名或密码!") ;//登录失败

}

}

}

});

reset.addActionListener(new ActionListener(){ //采用内部匿名类

public void actionPerformed(ActionEvent e){

if(e.getSource()==reset){ //判断触发器源是否是提交按钮

nameText.setText(""); //设置文本框中的内容

passText.setText(""); //设置文本框中的内容

infoLab.setText("服务器登陆系统"); //恢复标签显示

}

}

});

frame.addWindowListener(new WindowAdapter(){//加入窗口监听

public void windowClosing(WindowEvent e){ }

}); // 加入事件

frame.setLayout(null); //使用绝对定位

nameLab.setBounds(5,5,60,20); //设置标签的位置及大小

passLab.setBounds(5,30,60,20); //设置标签的位置及大小

infoLab.setBounds(5,65,220,30); //设置标签的位置及大小

nameText.setBounds(65,5,100,20); //设置文本域的位置及大小

passText.setBounds(65,30,100,20); //设置密码域的位置及大小

submit.setBounds(165,5,60,20); //设置按钮的位置及大小

reset.setBounds(165,30,60,20); //设置按钮的位置及大小

frame.add(nameLab); //向窗体加入标签

frame.add(passLab); //向窗体加入标签

frame.add(infoLab); //向窗体加入标签

frame.add(nameText); //向窗体加入文本框

frame.add(passText); //向窗体加入密码框

frame.add(submit); //向窗体加入按钮

frame.add(reset) ;//向窗体加入按钮

frame.setSize(280,130); //设置窗体大小

frame.getContentPane().setBackground(Color.green) ;//设置窗体的背景颜色

frame.setLocation(300,200) ;//设置窗体在电脑桌面上的位置

frame.setVisible(true); //显示窗口

while(f==false){ //当登录失败时,一直循环运行,

}

new MyServer();//显示窗体页面

}

}

验证登陆实现类 class LoginCheck

package com.server;

public class LoginCheck {

private String name ;//用户名

private String password ;//密码

//构造方法

public LoginCheck(String name,String password){

this.name = name ;//传递用户名

this.password = password ;//传递密码

}

//验证用户名和密码

public boolean validate(){

//验证方法

if("y".equals(name)"1".equals(password)){ //判断用户名和密码是否正确

return true; //返回true

}else{

return false ;//返回false

}

}

}

package com.server;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

import java.text.DateFormat;

import java.util.Date;

import javax.swing.*;

聊天实现类 class MyServer

public class MyServer {

protected JLabel lab10;

// 全体变量,做传递的一个组件

String s = "已经成功连接";

// 初始字符串,在两个聊天窗口链接成功时输出,同时作为两个窗口传递字符的一个变量

// 构造方法

public MyServer(){

try{//异常处理

JFrame frame=new JFrame("服务器窗口");

//设置窗体

frame.setLayout(null);

//让布局管理器为空,使用绝对定位

Font fnt=new Font("Serief",Font.PLAIN,40);//字体设置

Font fnt1=new Font("Serief",Font.PLAIN,20);//字体设置

//我的用户名显示

JLabel lab1=new JLabel("服务器名:",JLabel.LEFT);

//标签实例化,文本左对齐

lab1.setBounds(8, 10, 100, 20);

//设置组件位置及大小

frame.add(lab1);

//添加组件

JTextField text2=new JTextField(30); //单行文本输入组件

text2.setBounds(150, 10, 200, 20);//设置组件位置及大小

text2.setEnabled(false);//文本条不可编辑

text2.setText("笑笑聊天室");//输入内容

text2.setFont(fnt1);//设置字体

frame.add(text2);//添加组件

//服务器IP显示

JLabel lab2=new JLabel("当前服务器IP:",JLabel.LEFT);

//标签实例化,文本左对齐

lab2.setBounds(8, 45, 100, 20);//设置组件位置及大小

frame.add(lab2);//添加组件

JTextField text3=new JTextField(30);//单行文本输入组件

text3.setBounds(150, 45, 200, 20);//设置组件位置及大小

text3.setEnabled(false);

//文本不可编辑

text3.setText("127.0.0.1");//输入内容

text3.setFont(fnt1);//设置字体

frame.add(text3);

//添加组件

//服务器端口显示

JLabel lab3=new JLabel("当前服务器端口:",JLabel.LEFT);

//标签实例化,文本左对齐

lab3.setBounds(8, 80, 100, 20);//设置组件位置及大小

frame.add(lab3);//添加组件

JTextField text4=new JTextField(30);//单行文本输入组件

text4.setBounds(150, 80, 200, 20);//设置组件位置及大小

text4.setEnabled(false);//文本不可编辑

text4.setText("8888");//输入内容

text4.setFont(fnt1);//设置字体

frame.add(text4);//添加组件

//聊天记录显示

JLabel lab4=new JLabel("聊天记录如下:",JLabel.LEFT);

//标签实例化 文本左对齐

lab4.setBounds(8, 115, 100, 20);//设置组件位置及大小

frame.add(lab4);//添加组件

final JTextArea text1=new JTextArea();//多行文本输入组件

text1.setEnabled(false);//文本不可编辑

text1.setLineWrap(true);//自动换行

JScrollPane scr=new JScrollPane(text1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); //设置滚动条,水平和垂直滚动条始终显示

scr.setBounds(8, 150, 450, 350);//设置组件位置及大小

frame.add(scr);//添加组件

//聊天输入窗口及确定

JLabel lab5=new JLabel("请输入聊天内容:",JLabel.LEFT); //标签实例化,文本左对齐

lab5.setBounds(8, 500, 100, 20);//设置组件位置及大小

frame.add(lab5);//添加组件

final JTextArea text5=new JTextArea();//多行文本输入组件

text5.setLineWrap(true);//自动换行

JScrollPane scr2=new JScrollPane(text5,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);//设置滚动条,水平和垂直滚动条始终显示

scr2.setBounds(150, 500, 300, 50);//设置组件位置及大小

frame.add(scr2);//添加组件

final JButton but=new JButton("确定");//设置确定按钮

but.setFont(fnt);//添加字体设置

but.setBounds(480, 500, 200, 50);//设置组件位置及大小

but.addActionListener(

new ActionListener(){ //采用内部匿名类

public void actionPerformed(ActionEvent e){

if(e.getSource()==but){ //判断触发器源是否是提交按钮

text1.append("笑笑: "+lab10.getText()+"\n ");//在聊天记录上添加文本

text1.append(text5.getText()+"\n"); //将输入的聊天内容输出在聊天记录上

s=text5.getText(); //得到聊天内容

text5.setText(""); // 将聊天窗口内容设置为空

}

}

});

frame.add(but);//添加组件

//当前时间显示

JLabel lab7=new JLabel("时间显示:",JLabel.LEFT);//标签实例化,文本左对齐

lab7.setBounds(450, 20, 100, 20);//设置组件位置及大小

frame.add(lab7);//添加组件

DateFormat df=DateFormat.getDateTimeInstance();//取得系统时间

String df2= df.format(new Date()); //将时间转换成字符串

JLabel lab8=new JLabel(df2,JLabel.LEFT);//标签实例化,文本左对齐

lab8.setBounds(520, 20, 130, 20);//设置组件位置及大小

frame.add(lab8);//添加组件

lab10=lab8; //传递时间显示,以便能在聊天记录上显示记录时间

new Time(lab8); //使时间动态显示

//用户列表显示

JLabel lab6=new JLabel("用户列表:",JLabel.LEFT);//标签实例化,文本左对齐

lab6.setBounds(500, 40, 100, 20);//设置组件位置及大小

frame.add(lab6);//添加组件

JTextArea text6=new JTextArea();//标签实例化,文本左对齐

text6.setEnabled(false);//文本不可编辑

text6.setLineWrap(true);//自动换行

JScrollPane scr3=new JScrollPane(text6,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);//设置滚动条,水平和垂直滚动条始终显示

scr3.setBounds(460, 70, 220, 420);//设置组件位置及大小

frame.add(scr3);//添加组件

//窗口的属性

frame.setSize(700,600);//窗口大小

frame.getContentPane().setBackground(Color.pink);//窗口的背景颜色

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时关闭程序

frame.setLocation(100,50);//在电脑桌面上出现的位置

frame.setVisible(true);//显示窗口

//连个窗口连接

//建立Server Socket并等待连接请求

ServerSocket server =new ServerSocket(8889);

Socket socket=server.accept();

//连接建立,通过Socket获取连接上的输入/输出流

BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));

final PrintWriter out =new PrintWriter(socket.getOutputStream());

//先读取Client发送的数据,然后从标准输入读取数据发送给Client当接收到bye时关闭连接

String s1="",s2="";

//标志字符串,作为传递字符串使用

//得到其他窗口传递的字符串,并判断是否结束

while(!(s1=in.readLine()).equals("bye")){

text6.setText("可可在线"); //当连接成功是在用户列表中 输出用户名字

if(!s1.equals("")){ //如果传递的字符串不为 空

text1.append("可可: "+lab10.getText()+"\n ");//在聊天记录上添加文本

text1.append(s1+"\n"); //将输入的聊天内容输出在聊天记录上

}

s2=s;//将在聊天窗口中得到的字符串传递给输出字符串

for(;s2.equals("")||s2.equals(null);s2=s){//当传递的字符串为空时等待用户输入聊天内容

}

s="";//将在聊天窗口中得到的字符串设为空

if(!s2.equals("")!s2.equals(null)){// s2不为空时做

out.println(s2); //向其他窗口输出字符串

}

out.flush();//输出聊天内容

}

//关闭连接

in.close();

out.close();

socket.close();

server.close();

}catch(Exception e){

}

}

//main函数

public static void main(String args[]){

new Login();//登录实现 } }

}

}

时间类 class Time

package com.server;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.text.SimpleDateFormat;

import java.util.Date;

import javax.swing.JLabel;

import javax.swing.Timer; //时间类

public class Time {

public Time(JLabel time){

//构造方法 this.setTimer(time);

//设置时间

}

public void setTimer(JLabel time){

//设置时间方法

final JLabel varTime = time;

//传递组件

Timer timeAction = new Timer(1000, new ActionListener() {

//时间监听

public void actionPerformed(ActionEvent e) {

long timemillis = System.currentTimeMillis();//得到系统时间

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//转换日期显示格式

varTime.setText(df.format(new Date(timemillis)));//输出得到的时间

}

});

timeAction.start(); //开启线程

}

}

急需一个java编程实现的简单聊天窗口代码

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.net.*;

import java.io.*;

public class ClientDemo01 {

public static void main(String[] args){

JFrame f=new JFrame("AA");

JPanel p1=new JPanel();

JPanel p2=new JPanel();

JTextArea ta=new JTextArea(15,30);

ta.setEditable(false); //文本域只读

JScrollPane sp=new JScrollPane(ta); //滚动窗格

JTextField tf=new JTextField(20);

JButton b=new JButton("发送");

p1.add(sp);

p2.add(tf);

p2.add(b);

f.add(p1,"Center");

f.add(p2,"South");

f.setBounds(300,300,360,300);

f.setVisible(true);

f.setResizable(false);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Socket socket=null;

BufferedInputStream bis=null;

BufferedOutputStream bos=null;

try{

socket=new Socket("192.168.0.4",5000);

bis=new BufferedInputStream(socket.getInputStream());

bos=new BufferedOutputStream(socket.getOutputStream());

MyThread01 mt=new MyThread01(bis,ta);

mt.start();

}catch(Exception e){

e.printStackTrace();

}

b.addActionListener(new ButtonActionListener01(tf,ta,bos));

}

}

class ButtonActionListener01 implements ActionListener{

JTextField tf;

JTextArea ta;

BufferedOutputStream bos;

public ButtonActionListener01(JTextField tf,JTextArea ta,BufferedOutputStream bos){

this.tf=tf;

this.ta=ta;

this.bos=bos;

}

public void actionPerformed(ActionEvent e){

String message=tf.getText();

if(!message.equals("")){

tf.setText(""); //清空文本框

ta.append("AA:"+message+"\n"); //添加到文本域并换行

try{

bos.write(message.getBytes());

bos.flush();

}catch(Exception ex){

System.out.println("发送失败");

}

}

}

}

class MyThread01 extends Thread{

BufferedInputStream bis;

JTextArea ta;

public MyThread01(BufferedInputStream bis,JTextArea ta){

this.bis=bis;

this.ta=ta;

}

public void run(){

try{

while(true){

byte[] b=new byte[100];

int length=bis.read(b);

String message=new String(b,0,length);

ta.append("BB:"+message+"\n");

}

}catch(Exception e){

e.printStackTrace();

}

}

} import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.net.*;

import java.io.*;

public class ServerDemo01{

public static void main(String[] args){

JFrame f=new JFrame("BB");

JPanel p1=new JPanel();

JPanel p2=new JPanel();

JTextArea ta=new JTextArea(12,30); //文本域,第一个参数为行数,第二个参数为列数

ta.setEditable(false); //文本域只读

JScrollPane sp=new JScrollPane(ta); //滚动窗格

JTextField tf=new JTextField(20);

JButton b=new JButton("发送");

p1.add(sp);

p2.add(tf);

p2.add(b);

f.add(p1,"Center");

f.add(p2,"South");

f.setBounds(300,300,360,300);

f.setVisible(true);

f.setResizable(false);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

ServerSocket server=null;

Socket socket=null;

BufferedInputStream bis=null;

BufferedOutputStream bos=null;

try{

server=new ServerSocket(5000);

//ta.append("等待AA连接...\n");

socket=server.accept();

//ta.append("AA已连接\n");

bis=new BufferedInputStream(socket.getInputStream());

bos=new BufferedOutputStream(socket.getOutputStream());

MyThread1 mt=new MyThread1(bis,ta);

mt.start();

}catch(Exception e){

e.printStackTrace();

}

b.addActionListener(new ButtonActionListener1(tf,ta,bos));

}

}

class ButtonActionListener1 implements ActionListener{

JTextField tf;

JTextArea ta;

BufferedOutputStream bos;

public ButtonActionListener1(JTextField tf,JTextArea ta,BufferedOutputStream bos){

this.tf=tf;

this.ta=ta;

this.bos=bos;

}

public void actionPerformed(ActionEvent e){

String message=tf.getText(); //获取文本框中的内容

if(!message.equals("")){

tf.setText(""); //清空文本框

ta.append("BB:"+message+"\n"); //添加到文本域并换行

try{

bos.write(message.getBytes());

bos.flush();

}catch(Exception ex){

System.out.println("发送失败!");

}

}

}

}

class MyThread1 extends Thread{

BufferedInputStream bis;

JTextArea ta;

public MyThread1(BufferedInputStream bis,JTextArea ta){

this.bis=bis;

this.ta=ta;

}

public void run(){

try{

while(true){

byte[] b=new byte[100];

int length=bis.read(b);

String message=new String(b,0,length);

ta.append("AA:"+message+"\n");

}

}catch(Exception e){

e.printStackTrace();

}

}

}


本文题目:java聊天窗口代码 java聊天程序代码
URL标题:http://cdkjz.cn/article/ddcsijs.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220