java做的飞讯聊天系统源代码

合集下载

JAVA局域网聊天系统源代码

JAVA局域网聊天系统源代码

这是我自己做的简单聊天系统客户端package LiaoTianSys;import java.awt.*;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.io.*;import .Socket;import .UnknownHostException;public class ConversationFrame extends JFrame {JScrollPane jsp;JTextField jtf;static JTextArea jta;//JTextArea jat1,jta2;JButton enter=new JButton("发送");JButton jb=new JButton("聊天室好友");JButton jb2=new JButton("进入聊天室");JButton jb3=new JButton("刷新在线人员列表");JPanel jp,jp1,jp3,jp4;DefaultListModel listmodel = new DefaultListModel();//static String[] NAME=new String[10];String n[]={"f"};JList list=new JList(listmodel);JLabel time=new JLabel("当前系统时间:");JLabel showtime=new JLabel("显示时间");JLabel jl=new JLabel("输聊天信息");JLabel nicheng=new JLabel("昵称");JTextField NCshuru=new JTextField(10);static DataOutputStream dos;static DataInputStream dis;//final LoginFrame lf;Socket socket;public ConversationFrame(){Container con=getContentPane();con.setLayout(new BorderLayout());jp=new JPanel();setSize(700,600);setLocation(100,100);jta=new JTextArea();jta.setEditable(false);jsp=new JScrollPane(jta);con.add(jsp,BorderLayout.CENTER);jtf=new JTextField(20);jp.add(jl);jp.add(jtf);jp.add(enter);con.add(jp,BorderLayout.SOUTH);jp1=new JPanel(new BorderLayout());JScrollPane jsp1=new JScrollPane(list);jp1.add(jsp1,BorderLayout.CENTER);jp1.add(jb,BorderLayout.NORTH);con.add(jp1,BorderLayout.EAST);//pack();jp3=new JPanel();jp3.add(nicheng);jp3.add(NCshuru);jp3.add(jb2);con.add(jp3,BorderLayout.NORTH);jp4=new JPanel(new GridLayout(10,1));jp4.add(jb3);jp4.add(time);jp4.add(showtime);new getTime(this).start();con.add(jp4,BorderLayout.WEST);setVisible(true);// 发送信息给所有人enter.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent arg0) {// TODO Auto-generated method stubString info=jtf.getText();try {dos.writeUTF(NCshuru.getText()+" 对所有人说:"+info);dos.flush();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});//进入聊天室时将自己的昵称发给服务器,首先去验证是否会与已有的人同名,本聊天室是不支持同昵称聊天jb2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){String msg=NCshuru.getText().toString();//得到昵称if(msg.length()==0){JOptionPane.showMessageDialog(null, "昵称不应该为空,", "温馨提示", RMA TION_MESSAGE);}{try{dos.writeUTF("name"+msg);dos.flush();}catch(Exception ex){System.out.println(ex.getMessage());}}}});//向服务器请求更新在线人员列表jb3.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){try {listmodel.removeAllElements();//请求之前删除JList对象中的所有内容dos.writeUTF("请求更新在线人员列表");dos.flush();} catch (IOException e1) {// TODO Auto-generated catch block//e1.printStackTrace();System.out.println(e1.getMessage());}}});//当有在线人员时,双击JList列表某项弹出私聊对话框事件,匿名内部类实现的list.addMouseListener(new MouseAdapter(){public void mouseClicked(MouseEvent e){if(e.getClickCount()==2){int index=list.locationToIndex(e.getPoint());// 获得list表中的索引值String recevier=(String)listmodel.getElementAt(index);//得到索引对应的值String sender=NCshuru.getText();new Danliao(sender,recevier,socket);}}});}public static void main(String[] args) {ConversationFrame Con=new ConversationFrame();Con.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);Con.kaishi();}public void kaishi(){try {socket=new Socket("172.16.14.60",8888);dos=new DataOutputStream(socket.getOutputStream());dis=new DataInputStream(socket.getInputStream());pc pc1=new pc(socket,this);//传送套接字,本类对象给pc线程pc1.start();} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}// pc线程类,负责接收服务器发送来的信息class pc extends Thread{ ConversationFrame conver;Socket socket;public pc(Socket socket,ConversationFrame conver){this.conver=conver;this.socket=socket;}public void run(){try {int i=0;while(true){String line;//从线路读取信息line=ConversationFrame.dis.readUTF();// 将所有的在线人员昵称发送给JList,并添加到在线人列表中if(line.startsWith("N"))// 服务器发送过来的信息的格式是N+{String na=line.substring(1);try{conver.listmodel.addElement(na);System.out.println(na);}catch(Exception e){System.out.println(e.getMessage());}}//接受服务器发来的广播聊天信息else{ConversationFrame.jta.append(line+"\n");}}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println(e.getMessage());}}}服务器端package LiaoTianSys;import java.io.*;import .*;import java.util.*;public class Server implements Runnable{public static final int port=8888;protected ServerSocket ss;static Vector connections;Thread connect;public Server(){try {ss=new ServerSocket(port);connections=new Vector(1000);connect=new Thread(this);connect.start();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void main(String[] args) {new Server();}public void run(){try{while(true){Socket client=ss.accept();System.out.println("客户端连接上");firstthread f=new firstthread(this,client);f.setPriority(Thread.MIN_PRIORITY);f.start();connections.addElement(f);}}catch(IOException e){System.out.println(e.getMessage());}}//向所有人发送聊天信息public void SenAll(String msg){int i;firstthread ft;for(i=0;i<connections.size();i++){ft=(firstthread)connections.elementAt(i);try{ft.out.writeUTF(msg);}catch(Exception e){System.out.println(e.getMessage());}}}//发送单聊信息的方法public void SenOne(String msg){int i;firstthread ft;/*String s1,s2,s3;s1=new String("people");s2=new String(msg.substring(2));//私信为两个字s3=s1.conString msg="我悄悄的对小花说你好啊";cat(s2);*/int begin=msg.indexOf("对");int end=msg.indexOf("说");begin=begin+1;String strNew=msg.substring(begin,end);for(i=0;i<connections.size();i++)//遍历线程,找到要发送的对象{ft=(firstthread)connections.elementAt(i);//遍历线程if(strNew.startsWith()){System.out.println();try{String MSG=msg.substring(7);ft.out.writeUTF(MSG);}catch(IOException e){System.out.println(e.getMessage());}}}}}class firstthread extends Thread{protected Socket client;String line,name=null;DataOutputStream firstout,out;DataInputStream in;Server server;public firstthread(Server server,Socket socket){this.server=server;this.client=socket;try{in=new DataInputStream(client.getInputStream());out=new DataOutputStream(client.getOutputStream());firstout=new DataOutputStream(client.getOutputStream());}catch(IOException e){server.connections.removeElement(this);}}//客户线程运行的方法,不断监听客户线路发送的来的信息,然后决定转发方式public void run(){try{while(true){line=in.readUTF();if(line.startsWith("name")){//获取当前线程firstthreadd=(firstthread)(server.connections.elementAt(server.connections.indexOf(this)));line=line.substring(4);if(==null){=line;}}//将服务器的所有在线人员的昵称发送给所有的客户端else if(line.startsWith("请求更新在线人员列表")){try{for(int i=0;i<server.connections.size();i++){firstthread c=(firstthread)(server.connections.elementAt(i));if(!=null){firstout.writeUTF("N"+);//发送昵称}}}catch(Exception e){System.out.println(e.getMessage());}}else if(line.startsWith("private")){server.SenOne(line);}//发送聊天信息给所有的pc客户端else{server.SenAll(line);}}}catch(IOException e){System.out.println(e.getMessage());}}}显示时间package LiaoTianSys;import java.text.SimpleDateFormat;import java.util.Date;public class getTime extends Thread{String time;ConversationFrame conver;public getTime(ConversationFrame conver){this.conver=conver;System.out.println("获得系统时间");}public void run(){while(true){SimpleDateFormat df=new SimpleDateFormat("HH:mm:ss");time= df.format(new Date());//System.out.println(time);conver.showtime.setText(time);try{this.sleep(1000);}catch(Exception e){System.out.println(e.getMessage());}}}public static void main(String []args){}}单聊package LiaoTianSys;import java.io.DataOutputStream;import java.io.IOException;import .*;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Danliao extends JFrame implements ActionListener{ JButton jb=new JButton("发送");JPanel jp1=new JPanel();JLabel jl=new JLabel("输入聊天信息");JTextField jtf=new JTextField(20);JTextArea jta=new JTextArea();JScrollPane jsp=new JScrollPane(jta);String recevier;String sender;Socket socket;public Danliao(String sender,String recevier,Socket socket) { this.recevier=recevier;this.sender=sender;this.socket=socket;setBackground(Color.red);setTitle("与"+recevier+"单聊");setSize(400,400);setLocation(200,200);Container con=getContentPane();con.setLayout(new BorderLayout());con.add(jsp,BorderLayout.CENTER);jp1.add(jl);jp1.add(jtf);jp1.add(jb);/*addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){//System.exit(0);//this.dispose();//this.hide();this.setVisible(false);}});*/addWindowListener(new Close(this));con.add(jp1,BorderLayout.SOUTH);jb.addActionListener(this);setVisible(true);}public void actionPerformed(ActionEvent e){ String msg=jtf.getText();jta.append(msg+"\n"+"\n");jtf.setText(null);try{DataOutputStream dos=new DataOutputStream(socket.getOutputStream());dos.writeUTF("private"+sender+"悄悄的对"+recevier+"说: "+msg);jtf.setText(null);}catch(Exception e1){e1.printStackTrace();}}public static void main(String[] args){}}//单击关闭窗口事件,隐藏单聊窗口class Close extends WindowAdapter{Danliao danliao;public Close(Danliao danliao){this.danliao=danliao;}public void windowClosing(WindowEvent e) {danliao.setVisible(false);}}。

java聊天程序代码

java聊天程序代码

import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.io.*;public class ChatJFrame extends JFrame implements ActionListener {private JTextArea text_receiver; //显示对话内容的文本区private JTextField text_sender; //输入发送内容的文本行private PrintWriter cout; //字符输出流对象private String name; //网名public ChatJFrame(String name, String title, PrintWriter cout) //构造方法{super("聊天室"+name+" "+title);this.setSize(320,240);this.setLocation(300,240);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.text_receiver = new JTextArea();this.text_receiver.setEditable(false); //不可编辑this.add(this.text_receiver);JPanel panel = new JPanel();this.add(panel,"South");this.text_sender = new JTextField(12);panel.add(this.text_sender);this.text_sender.addActionListener(this); //注册单击事件监听器JButton button_send = new JButton("发送");panel.add(button_send);button_send.addActionListener(this);JButton button_leave = new JButton("离线");panel.add(button_leave);button_leave.addActionListener(this);this.setVisible(true);this.setWriter(cout); = name;}public ChatJFrame(){this("","",null);}public void setWriter(PrintWriter cout) //设置字符输出流对象{this.cout = cout;}public void receive(String message) //显示对方发来的内容{text_receiver.append(message+"\r\n");}public void actionPerformed(ActionEvent e){if (e.getActionCommand()=="离线"){if (this.cout!=null){this.cout.println(name+"离线");this.cout.println("bye");this.cout = null;}text_receiver.append("我离线\n");}else //发送{if (this.cout!=null){this.cout.println(name+" 说:"+text_sender.getText());text_receiver.append("我说:"+text_sender.getText()+"\n"); text_sender.setText("");}elsetext_receiver.append("已离线,不能再发送。

飞信Java手机客户端使用手册

飞信Java手机客户端使用手册

飞信Java手机客户端使用手册登录如果您已经订购了飞信的业务,打开飞信手机客户端JAVA版客户端程序,直接进入飞信手机客户端JAVA版登录窗口。

在登录飞信时,您无需输入手机号或者飞信号,以及登录密码,飞信根据登录手机号验证用户身份。

进入登录流程后,飞信首先进行登录初始化,然后开始登录飞信。

在登录过程中,您的手机会询问您:是否允许应用程序“飞信”使用网络,请选择“是”。

接着,您还要选择网络接入点,飞信使用的接入点为“移动梦网” 。

添加好友如果您知道对方的手机号码或者飞信号,您可以直接输入手机号码或者飞信号添加对方到您的好友列表中。

在飞信主窗口,选择[功能]进入“主菜单”后,选择[直接添加好友],进入“直接添加好友”窗口。

新添加的好友自动加入好友组。

发送消息/聊天在飞信主窗口的联系人列表中,选择一个联系人,按中心键进入“联系人操作菜单”,选择[发送消息]进入“写消息”窗口,编辑完消息后,选择[发送]开始与该联系人聊天。

也可以在选中好友的时候,选择右软键的“消息”进入消息编辑状态。

如果联系人不在线,您也一样可以给他发送消息,这时只要您的联系人手机能够接收和发送短消息,就可以和您继续聊天,进行无障碍的沟通。

语音聊天JAVA版不能直接通过客户端发起语聊,你可以先退出客户端发短信YY(语音)到12520+好友飞信号(如12520123456789)即可与好友语聊。

多人文字聊天您可以在飞信手机客户端JAVA版与多个好友同时聊天,您只需在多个聊天窗口间切换,即可与好友们畅所欲言。

在飞信主界面选择欲聊天的好友,发送消息。

按方向键右键进入[当前会话],从当前会话列表[打开]欲进入的会话。

在会话窗口选择[返回]进入[当前会话]窗口,重复进入会话操作,在多个会话间切换。

删除好友在好友组、陌生人组或者黑名单中选择您要删除的联系人,按中心键进入“联系人操作菜单”选择菜单中“删除”即可删除联系人。

在删除该用户时,您还可以选择是否同时阻止该用户。

(完整word版)聊天系统(客户端、服务器端) java版 完整代码(word文档良心出品)

(完整word版)聊天系统(客户端、服务器端) java版 完整代码(word文档良心出品)

客户端:import java.awt.*;import java.awt.event.*;import java.io.*;import .*;public class ChatClient extends Frame {Socket s = null;DataOutputStream dos = null;DataInputStream dis = null;private boolean bConnected = false;TextField tfTxt = new TextField();TextArea taContent = new TextArea();Thread tRecv = new Thread(new RecvThread());public static void main(String[] args) {new ChatClient().launchFrame();}public void launchFrame() {setLocation(400, 300);this.setSize(300, 300);add(tfTxt, BorderLayout.SOUTH);add(taContent, BorderLayout.NORTH);pack();this.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent arg0) {disconnect();System.exit(0);}});tfTxt.addActionListener(new TFListener());setVisible(true);connect();tRecv.start();}public void connect() {try {s = new Socket("127.0.0.1", 8888);dos = new DataOutputStream(s.getOutputStream());dis = new DataInputStream(s.getInputStream()); System.out.println("connected!");bConnected = true;} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public void disconnect() {try {dos.close();dis.close();s.close();} catch (IOException e) {e.printStackTrace();}/*try {bConnected = false;tRecv.join();} catch(InterruptedException e) {e.printStackTrace();} finally {try {dos.close();dis.close();s.close();} catch (IOException e) {e.printStackTrace();}}*/}private class TFListener implements ActionListener {public void actionPerformed(ActionEvent e) {String str = tfTxt.getText().trim();//taContent.setText(str);tfTxt.setText("");try {//System.out.println(s);dos.writeUTF(str);dos.flush();//dos.close();} catch (IOException e1) {e1.printStackTrace();}}}private class RecvThread implements Runnable {public void run() {try {while(bConnected) {String str = dis.readUTF();//System.out.println(str);taContent.setText(taContent.getText() + str + '\n');}} catch (SocketException e) {System.out.println("退出了,bye!");} catch (EOFException e) {System.out.println("推出了,bye - bye!");} catch (IOException e) {e.printStackTrace();}}}}服务器端import java.io.*;import .*;import java.util.*;public class ChatServer {boolean started = false;ServerSocket ss = null;List<Client> clients = new ArrayList<Client>();public static void main(String[] args) {new ChatServer().start();}public void start() {try {ss = new ServerSocket(8888);started = true;} catch (BindException e) {System.out.println("端口使用中....");System.out.println("请关掉相关程序并重新运行服务器!");System.exit(0);} catch (IOException e) {e.printStackTrace();}try {while(started) {Socket s = ss.accept();Client c = new Client(s);System.out.println("a client connected!");new Thread(c).start();clients.add(c);//dis.close();}} catch (IOException e) {e.printStackTrace();} finally {try {ss.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}class Client implements Runnable {private Socket s;private DataInputStream dis = null;private DataOutputStream dos = null;private boolean bConnected = false;public Client(Socket s) {this.s = s;try {dis = new DataInputStream(s.getInputStream());dos = new DataOutputStream(s.getOutputStream());bConnected = true;} catch (IOException e) {e.printStackTrace();}}public void send(String str) {try {dos.writeUTF(str);} catch (IOException e) {clients.remove(this);System.out.println("对方退出了!我从List里面去掉了!");//e.printStackTrace();}}public void run() {try {while(bConnected) {String str = dis.readUTF();System.out.println(str);for(int i=0; i<clients.size(); i++) {Client c = clients.get(i);c.send(str);//System.out.println(" a string send !");}/*for(Iterator<Client> it = clients.iterator(); it.hasNext(); ) {Client c = it.next();c.send(str);}*//*Iterator<Client> it = clients.iterator();while(it.hasNext()) {Client c = it.next();c.send(str);}*/}} catch (EOFException e) {System.out.println("Client closed!");} catch (IOException e) {e.printStackTrace();} finally {try {if(dis != null) dis.close();if(dos != null) dos.close();if(s != null) {s.close();//s = null;}} catch (IOException e1) {e1.printStackTrace();}}}}}。

JAVA实例(swing聊天室)源代码一服务端源码

JAVA实例(swing聊天室)源代码一服务端源码
ps.println(reStr);
ps.flush();
}
}
Socket s=ss.accept();
allSocket.add(s);
aSocket.put(s, String.&#118alueOf(i));
System.out.println(reStr);
}
for(Iterator iter=aSocket.keySet().iterator();iter.hasNext();){
try {
ServerSocket ss=new ServerSocket(8888);
int i=1;
while(true){
public static void main(String[] args) {
List<Socket> allSocket=new ArrayList<Socket>();
Map<Socket,String> aSocket=new HashMap<Socket,String>();
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
原文地址/操作时去掉此行
public class TcpQQServer {
String[] tempStr=reStr.split("-");
if("register".equals(tempStr[0])){
if(aSocket.containsKey(s)){

JAVA聊天程序设计代码及报告

JAVA聊天程序设计代码及报告

JAVA聊天程序设计代码及报告import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.PrintWriter;import java.util.Scanner;public class ChatClientpublic static void main(String[] args)final String HOST_NAME = "localhost";final int PORT_NUMBER = 1234;trySocket socket = new Socket(HOST_NAME, PORT_NUMBER);System.out.println("Connected to chat server!");BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream());PrintWriter writer = new PrintWriter(socket.getOutputStream(, true);// read user input in a separate threadThread inputThread = new Thread(( ->Scanner scanner = new Scanner(System.in);while (true)String userInput = scanner.nextLine(;writer.println(userInput);}});inputThread.start(;// continuously read server responsesString serverResponse;while ((serverResponse = reader.readLine() != null)System.out.println("Server: " + serverResponse);}} catch (Exception e)System.out.println("Error: " + e.getMessage();}}该聊天程序是一个基于TCP协议的客户端程序,使用了Java Socket 进行通信。

JAVA写的聊天工具源码

JAVA写的聊天工具源码
JLabel jLabel4 = new JLabel();
//Construct the frame
public ClientFrame() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
try {
jbInit();
}
catch (Exception e) {
jLabel3.setForeground(Color.blue);
jLabel3.setText("fill in user name");
link.setFont(new java.awt.Font("SansSerif", 0, 12));
link.setForeground(Color.blue);
jRadioButton2.setText("elect send");
jPanel2.setLayout(xYLayout3);
jScrollPane2.setMinimumSize(new Dimension(25, 25));
jLabel3.setFont(new java.awt.Font("SansSerif", 0, 12));
contentPane.add(jTextField2, new XYConstraints(4, 274, 316, 25));
contentPane.add(send, new XYConstraints(333, 246, -1, 24));
contentPane.add(exit, new XYConstraints(333, 276, 63, 24));

JAVA局域网聊天系统源代码

JAVA局域网聊天系统源代码

JAVA局域网聊天系统源代码【附件】附件1:JAVA局域网聊天系统源代码:zip【法律名词及注释】1:局域网(LAN):指在有限的地理范围内构建的计算机网络,用于连接位于同一建筑物或同一物理区域的计算机设备。

2:源代码(source code):指计算机程序的人类可读形式,通常采用编程语言编写的文本文件。

源代码需要经过编译才能转换为机器可执行的形式。

3:聊天系统(chat system):指一种通过计算机网络实现用户之间即时通信的系统,用户可以发送文字、图片、音频、视频等信息,并能够实时接收、查看其他用户发送的信息。

【正文】1:引言1.1 目的1.2 背景1.3 范围2:系统概述2.1 功能概述2.2 系统组成2.3 技术选型3:系统设计3.1 用例图3.2 类图3.3 数据库设计3.4 网络通信设计3.5 用户界面设计4:功能模块4.1 用户注册登录模块 4.1.1 注册功能4.1.2 登录功能4.2 好友管理模块4.2.1 好友列表展示 4.2.2 添加好友功能 4.2.3 删除好友功能4.3 聊天功能模块4.3.1 发送文本消息 4.3.2 发送图片消息 4.3.3 发送音频消息 4.3.4 发送视频消息 4.4 群组功能模块4.4.1 创建群组4.4.2 加入群组4.4.3 群组聊天5:系统实现5.1 开发环境5.2 开发工具5.3 源代码结构5.4 主要代码逻辑解析6:测试与部署6.1 单元测试6.2 集成测试6.3 UI测试6.4 部署配置7:系统运行与维护7.1 运行环境7.2 系统运行步骤7.3 常见问题与解决方法7.4 系统维护与升级【附件】附件1:JAVA局域网聊天系统源代码:zip【法律名词及注释】1:局域网(LAN):指在有限的地理范围内构建的计算机网络,用于连接位于同一建筑物或同一物理区域的计算机设备。

2:源代码(source code):指计算机程序的人类可读形式,通常采用编程语言编写的文本文件。

java聊天系统代码.

java聊天系统代码.

南华大学Java论文论文题目:c/s聊天系统专业09网络工程02班某某曾亚平〔20094360209〕某某X明〔20094360210〕某某龚泽辉20094360211〕某某X建〔20094360215〕C/S聊天系统组员:曾亚平〔20094360209〕,X明〔20094360210〕,龚泽辉20094360211〕,X建〔20094360215〕任务分配:服务器端的侦听局部〔X明,龚泽辉,X建〕、服务器端(曾亚平,X明)、客户端局部〔曾亚平,龚泽辉,X建〕摘要:随着互联网的快速开展,网络聊天工具已经作为一种重要的信息交流工具,受到越来越多的网民的青睐。

目前,出现了很多非常不错的聊天工具,其中应用比拟广泛的有Netmeeting、腾讯QQ、MSN-Messager等等。

该系统开发主要包括一个网络聊天服务器程序和一个网络聊天客户程序两个方面。

前者通过Socket套接字建立服务器,服务器能读取、转发客户端发来信息,并能刷新用户列表。

后者通过与服务器建立连接,来进展客户端与客户端的信息交流。

其中用到了局域网通信机制的原理,通过直接继承Thread类来建立多线程。

开发中利用了计算机网络编程的根本理论知识,如TCP/IP协议、客户端/服务器端模式〔Client/Server模式〕、网络编程的设计方法等。

在网络编程中对信息的读取、发送,是利用流来实现信息的交换,其中介绍了对实现一个系统的信息流的分析,包含了一些根本的软件工程的方法。

经过分析这些情况,该局域网聊天工具采用Eclipse为根本开发环境和java语言进展编写,首先可在短时间内建立系统应用原型,然后,对初始原型系统进展不断修正和改良,直到形成可行系统本论文通过java的Socket实现了一个基于局域网和网络的聊天室的程序的开发---基于java的C/S模式网络聊天室的设计与实现。

本论文详细介绍其设计和实现过程。

关键词:聊天客户端信息服务器端用Java实现C/S聊天系统C/S 〔Client/Server〕结构,即大家熟知的客户机和服务器结构。

基于JAVA实现网络聊天程序

基于JAVA实现网络聊天程序

基于JAVA实现网络聊天程序网络聊天程序是一种常见的应用,可以实现用户之间的即时通信。

本文将基于JAVA语言,介绍如何实现一个简单的网络聊天程序。

首先,我们需要了解网络聊天程序的基本需求。

一个简单的网络聊天程序通常包括以下功能:用户注册和登录、发送和接收消息、显示在线用户列表等。

接下来,我们将逐步实现这些功能。

第一步是创建一个用户类User,用于存储用户的信息,包括用户名和密码。

可以如下定义用户类:```javaclass Userprivate String username;private String password;public User(String username, String password)ername = username;this.password = password;}public String getUsernamreturn username;}public String getPassworreturn password;}```第二步是创建一个服务器类Server,用于接受和处理客户端的请求。

服务器类需要监听一个端口,接收客户端的连接请求,并启动一个线程来处理客户端的请求。

可以使用Java的Socket类和ServerSocket类来实现。

服务器类可以定义如下:```javaimport java.io.IOException;import java.util.ArrayList;import java.util.List;class Serverprivate List<Connection> connections = new ArrayList<>(;public void start(int port)tryServerSocket serverSocket = new ServerSocket(port);System.out.println("服务器已启动,监听端口:" + port);while (true)Socket socket = serverSocket.accept(;Connection connection = new Connection(socket); connection.start(;connections.add(connection);}} catch (IOException e)e.printStackTrace(;}}public void broadcast(String message)for (Connection connection : connections) connection.sendMessage(message);}}private class Connection extends Threadprivate Socket socket;private PrintWriter writer;public Connection(Socket socket)this.socket = socket;}public void rutryBufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream());writer = new PrintWriter(socket.getOutputStream(, true);String message;while ((message = reader.readLine() != null)System.out.println("收到消息:" + message);broadcast(message);}} catch (IOException e)e.printStackTrace(;} finallyconnections.remove(this);trysocket.close(;} catch (IOException e)e.printStackTrace(;}}}public void sendMessage(String message)writer.println(message);}}```以上是一个简单的服务器类,当有新的客户端连接时,服务器将创建一个新的连接对象并启动一个新的线程来处理客户端的请求。

java网络聊天编程及其代码

java网络聊天编程及其代码

java网络聊天编程及其代码网络聊天结合所学网络开发应用程序,本文将介绍一个网络聊天程序的开发过程,该程序使用了Swing设置的UI界面,并结合java语言多线程技术使网络聊天更加符合实际需要(可以不间断的,收发多条信息)。

最终效果如下程序的开发步骤如下:1、创建UDPmessage类,继承JFrame成为框体类,并实现ActionListener接口。

该类中包括多个成员变量,它们分别是信息接收文本域,信息发送文本框,IP文本框、“发送”按钮和数据包套接字。

2、在构造方法中初始化窗体组间,并将组间布局到窗体中,然后调用Server()方法创建数据包套接字,并添加“发送”按钮的事件监听器。

3、编写Server()方法,该方法负责创建DatagramSocket数据包套接字和接收信息的DatagramPacket数据包,最重要的是,该方法在线程中使用无限循环实现数据包的接收,这是网络程序设计必须掌握的接收数据的方法,这样才能保证数据的持续接收。

然后获取数据包中的IP信息,也就是数据包发送者的IP地址,这个IP地址将随数据包中的信息一起添加到信息接收文本域中,以区分信息的发布者。

4、实现ActionListener借口中的actionPerformed()方法,该方法用于处理“发送”按钮的单击事件,它需要获取ip文本框中的IP信息,这个IP地址将绑定到准备发送的数据包中。

5、编写本类的main()主方法,只需简单地创建主窗体对象就可以了。

实现代码如下:package qq;import java.awt.*;import java.awt.event.*;import java.io.IOException;import /doc/879825455.html,.*;import javax.swing.*;public class UDPmessage extends JFrame implements ActionListener { /****/private static final long serialVersionUID = 1L;private JTextArea text;//信息接收文本域private JTextField ipText;//IP文本框private JTextField sendText;//信息发送文本框private JButton button;//发送按钮private DatagramSocket socket;//数据报套接字private JScrollBar vsBar;//滚动条public UDPmessage(){setTitle("UDP聊天程序");//设置窗体标题setBounds(100,100,400,300);//窗体定位与大小setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//默认关闭操作为退出程序setLayout(new BorderLayout());//窗体使用边界布局管理器text=new JTextArea();//实例化信息接收文本域text.setEditable(false);//信息接收文本域不可编辑JScrollPane textPanel=new JScrollPane(text);//信息接收文本域添加滚动面板vsBar=textPanel.getVerticalScrollBar();//获取滚动面板的垂直滚动条add(textPanel,BorderLayout.CENTER);//添加滚动面板到窗体居中位置JPanel panel=new JPanel();//创建panel面板BorderLayout panelLayout=new BorderLayout();//创建边界布局管理器panelLayout.setHgap(5);//设置布局水平边界panel.setLayout(panelLayout);//将布局管理器注入panel面板ipText=new JTextField("192.168.***.***");//实例化IP文本框(请输入你自己IP地址)panel.add(ipText,BorderLayout.WEST);//添加文本框到panel 面板sendText=new JTextField();//实例化信息发送文本框panel.add(sendT ext,BorderLayout.CENTER);//添加信息发送文本框到panelbutton=new JButton("发送");//实例化发送按钮panel.add(button,BorderLayout.EAST);//添加按钮到panel面板add(panel,BorderLayout.SOUTH);//添加面板到窗体setVisible(true);//显示窗体server();//调用Server()方法button.addActionListener(this);//添加按钮事件监听器}private void server(){try{socket=new DatagramSocket(9527);//实例化数据报套接字byte[] buf=new byte[1024];final DatagramPacket dpl=newDatagramPacket(buf,buf.length);//创建接收数据的数据包Runnable runnable=new Runnable(){//定义线程public void run(){while(true){ //使用无限循环体try{Thread.sleep(100);//线程休眠时间为100mssocket.receive(dpl);//接收数据包int length=dpl.getLength();String message=new String(dpl.getData(),0,length);//获取数据包的字符串信息String ip=dpl.getAddress().getHostAddress();if(!InetAddress.getLocalHost().getHostAddress().equals(ip)) text.append(ip+":\n "+message+"\n");vsBar.setValue(vsBar.getMaximum());//控制信息滚动}catch(IOException e){e.printStackTrace();}catch(InterruptedException e){e.printStackTrace();}}}};new Thread(runnable).start();}catch(SocketException e){e.printStackTrace();}}public void actionPerformed(ActionEvent ev){try{String ip=ipText.getText();//获取IP文本框内容InetAddress address=InetAddress.getByName(ip);byte[] data=sendT ext.getText().getBytes();//获取发送的数据DatagramPacket dp=new DatagramPacket(data,data.length,address,9527);//定义数据包String myip=InetAddress.getLocalHost().getHostAddress();//获取本机IP//将发送信息添加到信息接收文本域中text.append(myip+":\n "+sendT ext.getText()+":\n");socket.send(dp);//发送数据包sendText.setText(null);}catch(UnknownHostException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();}}public static void main(String[] args) {UDPmessage udp= new UDPmessage();udp.setVisible(true);}}在两台计算机上分别运行,修改IP文本框中的IP地址为接收一方的IP,输入内容点击放松就可以接收了。

Java简易聊天工具课程设计报告及代码

Java简易聊天工具课程设计报告及代码

J a v a网络编程实践课程设计说明书课程名称:Java网络编程课程设计_题目:__基于C/S的班级聊天室(群聊)工具姓名:____HJC_____学号:201211012 201211006教学班号:软件工程1201班指导教师:xxx_______x x x x x x软件科学与工程系二○一三年十二月二十二日Java网络编程实践任务书目的:熟悉JA V A 语法,掌握图形化界面、多线程、网络、数据库等综合编程,掌握用编程语言开发由若干功能组成的小型项目的基本流程,增强动手实践能力,巩固和加强书本知识的学习,体会JA V A编程的特点。

题目1:基于C/S的班级即时通讯工具(2人)要求:1.C/S模式,基于Socket实现,服务器端用多线程来处理同时多个客户端连接。

2.数据存储:服务器端存储最少一个班级的信息;最好多个班级,主要存储班级若干学生的基本信息。

用数据库存储。

下面所有功能只考虑一个班是基本实现,考虑多个班是拓展实现。

3.界面:GUI界面,友好直观,布局合理,方便的功能入口。

4.功能:1)登陆输入用户名和密码;用户名是学号,有初始密码,例如111111;2)登陆验证根据服务器端存储的班级信息,对输入的用户进行验证,看是否存在于该班(只考虑一个班的情况)。

或是否是某个班的学生(多个班的情况)。

验证通过进入主界面,否则给出错误提示。

3)主界面列出该学生好友列表(同班级同学默认全是该生好友,如果是多个班则可以添加别班好友并经对方批准)。

4)即时聊天,选中某个好友,双击打开窗口聊天。

如果不在线则服务器等对方上线后转发(此功能属拓展实现)。

5)可以修改自己的登陆密码。

6)题目2:基于C/S的班级聊天室(群聊)工具(2人)要求:1.C/S模式,基于Socket实现,服务器端用多线程来处理同时多个客户端连接。

2.数据存储:服务器端存储一个班级的信息;主要存储班级若干学生的基本信息。

用数据库存储。

3.界面:GUI界面,友好直观,布局合理,方便的功能入口。

JAVA实例(swing聊天室)源代码一客户端源码

JAVA实例(swing聊天室)源代码一客户端源码

JAVA实例(swing聊天室)源代码一客户端源码.txt真正的好朋友并不是在一起有说不完的话题,而是在一起就算不说话也不会觉得尴尬。

你在看别人的同时,你也是别人眼中的风景。

要走好明天的路,必须记住昨天走过的路,思索今天正在走着的路。

import java.awt.BorderLayout;import java.awt.List;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.PrintStream;import .Socket;原文地址/操作时去掉此行import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;public class TcpQQClient extends JFrame{JButton btnConnection=new JButton("连接");//连接按钮JButton btnSend=new JButton("发送");//发送按钮JTextField txtServer=new JTextField(10);JTextField txtUser=new JTextField(10);JTextField txtContext=new JTextField(30);JLabel lblServer=new JLabel("服务器:");JLabel lblUser=new JLabel("用户名:");JLabel lblContext=new JLabel("内容:");JComboBox cmbUsers=new JComboBox();List lstMsg=new List(10,true);JPanel p1=new JPanel();JPanel p2=new JPanel();JPanel p3=new JPanel();JPanel p4=new JPanel();Socket s;//创建Socket对象public TcpQQClient(){super("QQ聊天");this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.setLayout(new BorderLayout());p1.setLayout(new BorderLayout());p1.add(lstMsg);p1.add(p3,BorderLayout.SOUTH);p2.add(lblUser);p2.add(txtUser);p2.add(lblServer);p2.add(txtServer);p2.add(btnConnection);cmbUsers.addItem("所有人");p3.add(cmbUsers);p3.add(lblContext);p3.add(txtContext);p3.add(btnSend);btnSend.setEnabled(false);btnSend.addActionListener(new ButtonMonitor());btnConnection.addActionListener(new ButtonMonitor());this.add(p2,BorderLayout.SOUTH);this.add(p1,BorderLayout.CENTER);this.pack();this.setVisible(true);}class ButtonMonitor implements ActionListener{public void actionPerformed(ActionEvent e) {if(e.getSource()==btnConnection){ //连接按钮try {//连接服务器s=new Socket(txtServer.getText(),8888); //获得输入流InputStream is=s.getInputStream();//创建输出流获取返回的套接字的输出流PrintStream ps=new PrintStream(s.getOutputStream(),true);ps.println("register-"+txtUser.getText());//启动ClientRehread类的线程--将信息将到启动ClientRehread类new Thread(new ClientRehread(lstMsg,is,cmbUsers,txtUser.getText())).start();TcpQQClient.this.btnSend.setEnabled(true);} catch (Exception e2) {System.out.println("客户端连接出错");}}if(e.getSource()==btnSend){//发送按钮try {PrintStream ps=new PrintStream(s.getOutputStream(),true);if("所有人".equals(cmbUsers.getSelectedItem())){ps.println("all-"+txtUser.getText()+"-"+txtContext.getText());}else{ps.println(cmbUsers.getSelectedItem()+"-"+txtUser.getText()+"-"+txtContext.getTe xt());}lstMsg.add("你对"+cmbUsers.getSelectedItem()+" 说:"+txtContext.getText());txtContext.setText("");} catch (Exception e2) {System.out.println("客户端发送信息出错");}}}}public static void main(String[] args) {new TcpQQClient();}}class ClientRehread implements Runnable{//线程-接收消息类List lstMsg;InputStream is;JComboBox cmbUsers;String user;public ClientRehread(List lstMsg, InputStream is,JComboBox cmbUsers,String user) {this.lstMsg = lstMsg;this.is = is;this.cmbUsers=cmbUsers;er=user;}public void run() {try {BufferedReader br=new BufferedReader(new InputStreamReader(is));while(true){String reStr=br.readLine();String[] str=reStr.split("-");if("register".equals(str[0])){this.cmbUsers.removeAllItems();this.cmbUsers.addItem("所有人");for(int i=1;i<str.length;i++){this.cmbUsers.addItem(str[i]); }}else if("all".equals(str[0])){if(!user.equals(str[1])){lstMsg.add(str[1]+" 对所有人说:"+str[2]);}}else if(user.equals(str[0])){lstMsg.add(str[1]+" 对你说:"+str[2]); }lstMsg.makeVisible(lstMsg.getItemCount()-1); //设置最后一项可见}} catch (Exception e) {e.printStackTrace();System.out.println("客户端接受信息出错");}} }。

JAVA聊天程序设计代码及报告

JAVA聊天程序设计代码及报告

一.系统需求分析网络聊天室通常直称聊天室;是一种人们可以在线交谈的网络论坛;在同一聊天室的人们通过广播消息进行实时交谈..在当今信息时代;越来越多的聊天工具被应用;java语言是当今流行的网络编程语言;它具有面向对象;与平台无关;安全;多线程等特点..使用java语言不仅可以实现大型企业级的分布式应用系统;还能够为小型的的;嵌入式设备进行应用程序的开发..面向对象的开发是当今世界最流行的开发方法;它不仅具有更贴近自然地语义;而且有利于软件的维护和继承;锻炼我们熟练地应用面向对象的思想和设计方法解决实际问题的能力..本程序正是用java语言实现了简单聊天功能..它是图形界面;线程;流与文件系统等技术的综合应用..其界面主要采用了java.awt包;java.swing包等..二.系统总体设计1.对性能的规定由于本软件知识一个聊天程序;程序只提供用户之间的聊天功能;故对网络传输数据要求不是很高;只要正常的传输速度就可以了..2数据管理IP地址IP;端口Port3.开发环境本软件采用Java语言编写;Java语言是一种跨平台的编程语言;所以本软件对操作系统没有特别的要求..而网络传输方面采用TCP/IP网络传输协议或者是RMI..4.设计概要1本软件客户端与用户共用一段程序..客户端编译运行后;在窗口选择----侦听..用户编译运行后;在窗口选择----连接..2本软件实现的功能有1允许服务器侦听客户端;客户端连接到服务器2允许服务区与客户端之间进行聊天;3允许服务器与客户端更改背景颜色;4 允许服务器与客户端更改字体颜色;5服务器与客户端时;会显示内容发送时间;6允许服务器与客户端用鼠标点击“发送”;按ENTER键均可发送内容7允许服务器与客户端用鼠标点击关闭时关闭聊天窗口三.系统详细设计1.代码功能描述1程序中引入的包:import java.awt.;import java.awt.event.;import javax.swing.;import java.;import java.io.;2代码中自定义的类:类名:chatHouse继承的类:JFrame实现的接口:ActionListener; Runnable作用:构造服务器界面以及客户端界面..定义的对象: TextArea ta;JTextField ip;JTextField port;JButton btn_server;JButton btn_client;JButton btn_backGroundCol;JButton btn_fontCol;JTextField send_text;JButton btn_send;JButton btn_close;JLabel pic;Socket skt;构造方法:public chatHouse主要成员方法:public void runpublic void actionPerformedActionEvent epublic void doServerpublic void doSend2.源代码chatHouse.javaimport java.awt.;import java.awt.event.;import javax.swing.;import java.;import java.io.;import java.util.;public class chatHouse extends JFrame implements ActionListener; Runnable{private TextArea ta;private JTextField ip;private JTextField port;private JButton btn_server;private JButton btn_client;private JButton btn_backGroundCol;private JButton btn_fontCol;private JTextField send_text;private JButton btn_send;private JButton btn_close;private JLabel pic;private Socket skt;public void run{try{BufferedReader br = new BufferedReadernew InputStreamReaderskt.getInputStream;whiletrue{String s = br.readLine; // 从网络读ifs==null break;ta.appends + "\n";}}catchException e{e.printStackTrace;}}public void actionPerformedActionEvent e{ife.getSource==btn_server{doServer;}ife.getSource==btn_client{doClient;}ife.getSource==btn_send{doSend;}}public void doServer{try{ServerSocket server = newServerSocketInteger.parseIntport.getText;skt = server.accept;ta.append"连接成功\n";new Threadthis.start;}catchException e{ta.append"服务器启动失败\n";}}public void doClient{try{skt = new Socketip.getText; Integer.parseIntport.getText;ta.append"连接成功\n";new Threadthis.start;}catchException e{ta.append"连接失败\n";}}public void doSend{Calendar c=Calendar.getInstance;int y=c.getc.YEAR;int M=c.getc.MONTH+1;int d=c.getc.DAY_OF_MONTH;int h=c.getc.HOUR_OF_DAY;int mm=c.getc.MINUTE;int ss=c.getc.SECOND;try{PrintWriter pw = new PrintWriterskt.getOutputStream;String s = send_text.getText;ifs==null return;ta.appendy+"-"+M+"-"+d+" "+h+":"+mm+":"+ss+"\n";ta.appends+"\n";pw.printlny+"-"+M+"-"+d+" "+h+":"+mm+":"+ss;pw.printlns;pw.flush;send_text.setText"";}catchException e{ta.append"发送失败\n";}}public chatHouse{super"聊天室";this.setBounds100;100;550;430;Container cc = this.getContentPane;JPanel p1 = new JPanel;cc.addp1; BorderLayout.NORTH;JPanel p2 = new JPanel;cc.addp2;BorderLayout.CENTER;JPanel p3 = new JPanel;cc.addp3;BorderLayout.SOUTH;pic=new JLabelnew ImageIcon"12.gif";cc.addpic;BorderLayout.EAST;p1.addnew JLabel"IP: ";ip = new JTextField"127.0.0.1"; 10;p1.addip;p1.addnew JLabel"Port: ";port = new JTextField"7777"; 4;p1.addport;btn_server = new JButton"侦听";p1.addbtn_server;btn_client = new JButton"连接";p1.addbtn_client;btn_backGroundCol =new JButton"背景色";p1.addbtn_backGroundCol;btn_fontCol =new JButton"字体颜色";p1.addbtn_fontCol;p2.setLayoutnew BorderLayoutta = new TextArea;p2.addta; BorderLayout.CENTER;send_text = new JTextField"Hello.";p2.addsend_text; BorderLayout.SOUTH;btn_send = new JButton"发送";p3.addbtn_send; BorderLayout.WEST;btn_close =new JButton"关闭";p3.addbtn_close; BorderLayout.CENTER;//---------------------------------------"关闭"按钮监听器 btn_close.addActionListenernew ActionListener{public void actionPerformedActionEvent e{System.exit100;}};//--------------------------------------- 背景变色监听btn_backGroundCol.addActionListenernew ActionListener{public void actionPerformedActionEvent e{JColorChooser chooser4=new JColorChooser;Color color=chooser4.showDialognull;"背景颜";Color.yellow; ta.setBackgroundcolor;}};//---------------------------------------字体变色监听btn_fontCol.addActionListenernew ActionListener{public void actionPerformedActionEvent e{JColorChooser chooser4=new JColorChooser;Color color=chooser4.showDialognull;"字体颜色";Color.black; send_text.setForegroundcolor;ta.setForegroundcolor;}};//---------------------------------------按ENTER键可发送监听btn_server.addActionListenerthis;btn_client.addActionListenerthis;btn_send.addActionListenerthis;setDefaultCloseOperationJFrame.EXIT_ON_CLOSE;send_text.addKeyListenernew KeyAdapter{public void keyPressedKeyEvent e{ife.getKeyCode==KeyEvent.VK_ENTERdoSend;}};}public static void mainString args{new chatHouse.setVisibletrue;}}import java.util.;3.程序测试编译运行程序后;先选择对方IP;选择同样的Port..服务器先侦听;客户端再连接..连接成功;窗口会显示“连接成功”字样..接下来就可以聊天了..1 服务器与客户端聊天..2服务器与客户端聊天..服务器将背景颜色设为粉红;字体颜色设为蓝色.. 客户端将背景颜色设为蓝色;字体颜色设为红色..四.小结1.通过本次课程设计;使得自己懂得理论和实践相结合起来;从理论中得出结论;才能真正掌握这门技术;也提高了自己独立思考的能力;在设计的过程中;可以自己解决..真正体会到要将一门知识学的更深入;必须加强实践;多练习;才能发现问题所在..2..本程序实现的功能还比较简单不够完善;从中;我知道了自己的不足之处;决心增长自己的知识;设计更加好的程序;实现各种更加复杂的功能;如:传输文件;图片..以及登陆界面;昵称等..3.总的来说;这次实训对我很有帮助..让我学会了的不只是设计JAVA聊天室;更让我学会主动学习;而不是被动接收..这样才能更好的运用自己所学到的知识..另:附该代码所用到的图片 12.gif。

pulsar java代码

pulsar java代码

pulsar java代码以下是一个简单的示例,演示了如何在Java中使用Pulsar客户端发送和接收消息:java.import org.apache.pulsar.client.api.;public class PulsarExample {。

public static void main(String[] args) throws PulsarClientException {。

PulsarClient client = PulsarClient.builder()。

.serviceUrl("pulsar://localhost:6650")。

.build();// 生产者发送消息。

Producer<String> producer =client.newProducer(Schema.STRING)。

.topic("my-topic")。

.create();producer.send("Hello, Pulsar!");// 消费者接收消息。

Consumer<String> consumer =client.newConsumer(Schema.STRING)。

.topic("my-topic")。

.subscriptionName("my-subscription")。

.subscribe();Message<String> msg = consumer.receive();System.out.println("Received message: " + msg.getValue());consumer.acknowledge(msg);client.close();}。

}。

在这个示例中,我们首先创建了一个Pulsar客户端,然后创建了一个生产者,用于向名为“my-topic”的主题发送消息。

java聊天工具源代码

java聊天工具源代码

源代码项目QQClientProject:LoguiGui代码:package com.huaxia.qq.mzz.gui;import mon.Message; import mon.MessageService; import er;import .Socket;import javax.swing.JOptionPane;public class LoguiGui extends javax.swing.JFrame {public LoguiGui() {initComponents();}public Socket connectServer() {Socket s = null;try {s = new Socket("127.0.0.1", 6666);} catch (Exception e) {e.printStackTrace();}return s;}private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {// TODO add your handling code here:String name = nameItem.getText();System.out.println("用户名:" + name);if (name == null || "".equals(name)) {JOptionPane.showMessageDialog(this, "用户名不能为空,请输入", "异常提示", JOptionPane.ERROR_MESSAGE);return;}String pwd = new String(pwdItem.getPassword());System.out.println("密码:" + pwd);if (pwd.length() == 0) {JOptionPane.showMessageDialog(this, "密码不能为空,请输入", "异常提示", JOptionPane.ERROR_MESSAGE);return;}final Socket s = this.connectServer();//构造消息. final User u = new User(name, pwd);Message msg = new Message(1, u);//执行发送MessageService.getInstance().sendMsg(msg, s);//接受消息【接收注册结果】Message result = MessageService.getInstance().receiveMsg(s);// 取出注册成功的标志String r = (String) result.getBody();if (r == null) {//注册成功java.awt.EventQueue.invokeLater(new Runnable() {public void run() {new ChatGui(u, s).setVisible(true);}});this.dispose();} else {JOptionPane.showMessageDialog(this, "登录失败:" + r, "异常提示", RMATION_MESSAGE);}private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here:final LoguiGui gui = this;java.awt.EventQueue.invokeLater(new Runnable() {public void run() {RegiterGui dialog = new RegiterGui(gui, true);dialog.setLocationRelativeTo(gui);dialog.setVisible(true);}});}private void jButton2MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here:nameItem.setText(null);pwdItem.setText(null);}public static void main(String args[]) {java.awt.EventQueue.invokeLater(new Runnable() {public void run() {new LoguiGui().setVisible(true);}});}RegiterGui代码:package com.huaxia.qq.mzz.gui;import mon.Message; import mon.MessageService; import er;import .Socket;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.util.Arrays;import javax.swing.JOptionPane;public class RegiterGui extends javax.swing.JDialog {private static final String url = "jdbc:odbc:mydata";private static final String user = "mzz";private static final String pwd = "mzz";public Socket connectServer() {Socket s = null;try {s = new Socket("127.0.0.1", 6666);} catch (Exception e) {e.printStackTrace();}return s;}private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:String name = nameItem.getText();System.out.println("用户名:" + name);char[] pwd0 = pwdItem.getPassword();String pwd1 = new String(pwd0);System.out.println("密码:" + pwd1);char[] pwd2 = pwdItem1.getPassword();String pwd3 = new String(pwd2);if (name == null || "".equals(name)) {JOptionPane.showMessageDialog(this, "用户名不能为空,请输入", "异常提示", JOptionPane.ERROR_MESSAGE);return;}if (pwd0.length == 0) {JOptionPane.showMessageDialog(this, "密码不能为空,请输入", "异常提示", JOptionPane.ERROR_MESSAGE);return;}if (pwd2.length == 0) {JOptionPane.showMessageDialog(this, "密码不能为空,请确认", "异常提示", JOptionPane.ERROR_MESSAGE);return;}if (!Arrays.equals(pwd0, pwd2)) {JOptionPane.showMessageDialog(this, "密码输入错误,请重新输入", "异常提示", JOptionPane.ERROR_MESSAGE);return;}String sex = null;if (sex1.isSelected()) {sex = sex1.getText();System.out.println("性别:" + sex);} else if (sex2.isSelected()) {sex = sex2.getText();System.out.println("性别:" + sex);} else if (sex3.isSelected()) {sex = sex3.getText();System.out.println("性别:" + sex);}String hobby =null;if (hobby1.isSelected()) {hobby = hobby1.getText();System.out.println("爱好:" + hobby);} else if (hobby2.isSelected()) {hobby = hobby2.getText();System.out.println("爱好:" + hobby);} else if (hobby3.isSelected()) {hobby =hobby3.getT ext();System.out.println("爱好:" + hobby);}String birth = yearItem.getText() + "年" + "" + monthItem.getT ext() + "月";System.out.println("生日:" + birth);String city = (String) (cityItem.getSelectedItem());System.out.println("城市:" + city);String profession = professionItem.getText();System.out.println("职业:" + profession);Socket s = this.connectServer();//构造消息User u = new User(name, pwd1, sex, hobby, birth, city, profession); Message msg = new Message(0, u);//执行发送MessageService.getInstance().sendMsg(msg, s);//接受消息【接收注册结果】Message result = MessageService.getInstance().receiveMsg(s);// 取出注册成功的标志String r = (String) result.getBody();if (r == null) {//注册成功JOptionPane.showMessageDialog(this, "注册成功", "提示", RMATION_MESSAGE);} else {JOptionPane.showMessageDialog(this, "" + r + "", "异常提示", RMATION_MESSAGE);}private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {// TODO add your handling code here:nameItem.setText(null);pwdItem.setText(null);pwdItem1.setText(null);sex2.setSelected(true);yearItem.setText(null);monthItem.setText(null);hobby1.setSelected(false);hobby2.setSelected(false);hobby3.setSelected(false);cityItem.setSelectedItem("请选择");professionItem.setText(null);}public static void main(String args[]) {java.awt.EventQueue.invokeLater(new Runnable() {public void run() {RegiterGui dialog = new RegiterGui(new javax.swing.JFrame(), true);dialog.addWindowListener(new java.awt.event.WindowAdapter() {public void windowClosing(java.awt.event.WindowEvent e) {System.exit(0);}});dialog.setVisible(true);}});}ChatGui代码:package com.huaxia.qq.mzz.gui;import mon.Message; import mon.MessageService; import er;import .Socket;import java.util.List;import javax.swing.DefaultListModel;import javax.swing.JList;import javax.swing.JOptionPane;public class ChatGui extends javax.swing.JDialog { private User u;private Socket s;final static int MAXUSER=100;public ChatGui(User u, Socket s) { initComponents();this.u = u;this.s = s;this.setTitle(u.getUserName());//秘书类,用以不断的接收消息new ClientWorker(s, this).start();}public JList getUsersListItem() {return usersListItem;}public void setUsersChatItem(String usersChat) {String s=this.newItem.getText()+usersChat;this.newItem.setText(s);}public void addUsers(List<User> list) {DefaultListModel dlm = (DefaultListModel) usersListItem.getModel(); for (User u : list) {dlm.addElement(u);}}public void addNewUser(User u) {DefaultListModel dlm = (DefaultListModel) usersListItem.getModel();dlm.addElement(u);}public void delUser(User curu) {DefaultListModel dlm = (DefaultListModel) usersListItem.getModel(); dlm.removeElement(curu);}private void formWindowClosing(java.awt.event.WindowEvent evt) { // TODO add your handling code here:Message msg = new Message(5, u);//发送消息给服务器MessageService.getInstance().sendMsg(msg, s);System.exit(0);//结束系统}private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {// TODO add your handling code here:String text = textItem.getText();if (text == null || "".equals(text)) {JOptionPane.showMessageDialog(this, "发送内容不能为空,请输入", "异常提示", JOptionPane.ERROR_MESSAGE);return;}User[] CUser=new User[MAXUSER];String UsersName;int i=0;Object[] listname =usersListItem.getSelectedValues();if(listname.length==0){JOptionPane.showMessageDialog(this, "请在在线好友中选择你要聊天的好友", "异常提示", RMATION_MESSAGE);return;}for(Object a:usersListItem.getSelectedValues()){CUser[i]=(User)a;i++;}int j=0;UsersName=CUser[j].getUserName();j++;for(;CUser[j]!=null;j++){UsersName=UsersName+","+CUser[j].getUserName();}String UsersText=this.newItem.getText()+"\n"+"您向"+UsersName+"发送消息:\n"+this.textItem.getText()+"\n";this.newItem.setText(UsersText);Message chat2=new Message(4,u,CUser,text);MessageService.getInstance().sendMsg(chat2, s);textItem.setText(null);}private void scriptMouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here:textItem.getSelectedTextColor();}private void colorMouseClicked(java.awt.event.MouseEvent evt) {// TODO add your handling code here:}private void jButton2MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here:newItem.setText(null);}ClientWorker代码:package com.huaxia.qq.mzz.gui;import mon.Message; import mon.MessageService; import er;import .Socket;import java.util.List;public class ClientWorker extends Thread{private Socket s;//登陆成功的管道private ChatGui gui;public ClientWorker(Socket s,ChatGui gui){this.s=s;this.gui=gui;}public void run(){//不断地接收消息,并处理while(true){Message msg=MessageService.getInstance().receiveMsg(s); //处理消息if(msg.getType()==2){//在线列表//从消息体拿出链表(包含的是在线用户)List<User> list=(List<User>)msg.getBody();gui.addUsers(list);}else if(msg.getType()==3){//新用户上线User curU=(User)msg.getBody();gui.addNewUser(curU);}else if(msg.getType() == 4) //聊天{User[] CUser=new User[gui.MAXUSER];int j=0;String[] HUser=new String[1024] ;int i=0;String Us=msg.getSend().getUserName();String s=msg.getSend().getUserName()+"向您发送信息:\n"+msg.getBody()+"\n";gui.setUsersChatItem(s);}else if(msg.getType()==5){//处理离线消息User curu=(User)msg.getBody();//获取药离线的用户gui.delUser(curu);}else{System.out.println("消息类型错误");}}}}项目QQCommonProjectDBHelper代码:package mon;import java.sql.Statement;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;public class DBHelper {private static final String url="jdbc:odbc:mydata"; private static final String name="mzz";private static final String pwd="mzz";private final static DBHelper impl=new DBHelper(); private DBHelper(){}public static DBHelper getInstance(){return impl;}public Connection getConnection(){try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); }catch(Exception e){e.printStackTrace();}Connection con=null;try{con=DriverManager.getConnection(url,name,pwd); }catch(Exception e){e.printStackTrace();}return con;}public boolean isUserExits(String userName){ Connection con=this.getConnection(); PreparedStatement pstm=null;ResultSet rs=null;boolean result=false;try{pstm=con.prepareStatement("select 1 from mz where userName=?");pstm.setString(1, userName);rs=pstm.executeQuery();while(rs.next()){result=true;}}catch(Exception e){e.printStackTrace();}finally{closeAll(rs,pstm,con);}return result;}public void closeAll(ResultSet rs,Statement pstm,Connection con){ try{if(rs!=null)rs.close();if(pstm!=null)pstm.close();if(con!=null)con.close();}catch(Exception e){e.printStackTrace();}}public boolean doRegister(User u) {Connection con=this.getConnection();PreparedStatement pstm=null;int result=0;try{pstm=con.prepareStatement("insert into mz (userName,userPwd,sex,hobby,birth,city,profession) values(?,?,?,?,?,?,?)");pstm.setString(1, u.getUserName());pstm.setString(2,u.getUserPwd());pstm.setString(3, u.getsex());pstm.setString(4, u.gethobby());pstm.setString(5, u.getbirth());pstm.setString(6, u.getcity());pstm.setString(7,u.getprofession());result=pstm.executeUpdate();}catch(Exception e){e.printStackTrace();}finally{closeAll(null,pstm,con);}return result==1;}public boolean doLogui(User u) {Connection con=this.getConnection();PreparedStatement pstm=null;ResultSet rs=null;boolean result=false;try{pstm=con.prepareStatement("select 1 from mz where userName=? and userPwd=?");pstm.setString(1, u.getUserName());pstm.setString(2, u.getUserPwd());rs=pstm.executeQuery();while(rs.next()){result=true;}}catch(Exception e){e.printStackTrace();}finally{closeAll(rs,pstm,con);}return result;}}Message代码:package mon; import java.io.Serializable;public class Message implements Serializable{//消息类型0: 注册1:登陆2: 用户列表 3 :新用户上线4: 聊天5: 离线private int type;//消息的发送人private User send;//消息的目的地private User[] tos;//消息内容private Object body;public Message(int type) {this.type = type;}public Message() {}public Message(int type, Object body) {this.type = type;this.body = body;}public Message(int type, User send, Object body) {this.type = type;this.send = send;this.body = body;}public Message(int type, User send, User[] tos, Object body) { this.type = type;this.send = send;this.tos = tos;this.body = body;}public Object getBody() {return body;}public void setBody(Object body) {this.body = body;}public User getSend() {return send;}public void setSend(User send) { this.send = send;}public User[] getTos() {return tos;}public void setTos(User[] tos) { this.tos = tos;}public int getType() {return type;}public void setType(int type) { this.type = type;}@Overridepublic String toString() {return "Message{" + "type=" + type + "send=" + send + "tos=" + tos + "body=" + body + '}';}}MessageService代码:package mon;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import .Socket;public class MessageService {private MessageService(){}private static final MessageService impl=new MessageService();public static MessageService getInstance(){return impl;}public void sendMsg(Message msg,Socket s){//获取管道中的流兵器和对象流连接起来try{ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());oos.writeObject(msg);oos.flush();}catch(Exception e){e.printStackTrace();}}public Message receiveMsg(Socket s){Message msg=null;//获取管道中的流兵器和对象流连接起来try{ObjectInputStream oos=new ObjectInputStream(s.getInputStream()); msg=(Message)oos.readObject();}catch(Exception e){e.printStackTrace();}return msg;}}User代码:package mon;import java.io.Serializable;public class User implements Serializable{private String userName;private String userPwd;private String birth;private String sex;private String hobby;private String city;private String profession;public User(String userName, String userPwd) { erName = userName;erPwd = userPwd;}public User(String userName, String userPwd, String sex, String hobby, String birth, String city, String profession) {erName = userName;erPwd = userPwd;this.sex = sex;this.hobby = hobby;this.birth=birth;this.city=city;this.profession=profession;}public String getUserName() {return userName;}public void setUserName(String userName) {erName = userName;}public String getUserPwd() {return userPwd;}public void setUserPwd(String userPwd) { erPwd = userPwd;}public String getsex() {return sex;}public void setsex(String sex) {this.sex = sex;}public String gethobby() {return hobby;}public void sethobby(String hobby) { this.hobby = hobby;}public String getbirth() {return birth;}public void setbirth(String birth) {this.birth=birth;}public String getcity() {return city;}public void setcity(String city) {this.city=city;}public String getprofession() {return profession;}public void setprofession(String profession) { this.profession=profession;}@Overridepublic boolean equals(Object obj) {if (obj == null) {return false;}if (getClass() != obj.getClass()) {return false;}final User other = (User) obj;if((erName==null)?(erName!=null):!erName.eq uals(erName)) {return false;}return true;}@Overridepublic int hashCode() {int hash = 3;hash = 17 * hash + (erName != null ?erName.hashCode() : 0);return hash;}@Overridepublic String toString() {return userName;}}项目QQServerProject:QQServer代码:package qqserverproject;import .ServerSocket;import .Socket;public class QQServer {public static void main(String[] args){//构造网络服务try{ServerSocket ss=new ServerSocket(6666);while(true){//启动网络服务Socket s=ss.accept();//有客户端来访问,启动秘书类new ServerWorker(s).start();}}catch(Exception e){e.printStackTrace();}}}ServerWorker代码:package qqserverproject;import mon.DBHelper; import mon.Message; import mon.MessageService; import er;import .Socket;import java.util.ArrayList;.import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Set;public class ServerWorker extends Thread {//在线用户列表private static Map<User, Socket> usersOnLine = new HashMap<User, Socket>();private Socket s;ServerWorker(Socket s) {this.s = s;}public void run() {//处理客户端请求//(1)注册的(2)登陆的(3)聊天的。

java 聊天室源码

java 聊天室源码

【ClientSocketDemo。

java 客户端Java源代码】import java。

net。

*;import java。

io.*;public class ClientSocketDemo{//声明客户端Socket对象socketSocket socket = null;//声明客户器端数据输入输出流DataInputStream in;DataOutputStream out;//声明字符串数组对象response,用于存储从服务器接收到的信息String response[];//执行过程中,没有参数时的构造方法,本地服务器在本地,取默认端口10745 public ClientSocketDemo(){try{//创建客户端socket,服务器地址取本地,端口号为10745socket = 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。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
}
});
}
}
});
f.add(t1);
JButton b3 = new JButton("锟揭伙");
JLabel mm = new JLabel("锟斤拷锟斤拷:");
mm.setBounds(100, 30, 0, 0);
mm.setSize(200, 245);
f.add(mm);
t1.setBounds(133, 102, 0, 0);
setIconImage(image);
setLayout(null);
Container f = getContentPane();//锟斤拷锟斤拷一锟斤拷锟斤拷签
setBounds(520, 250, 340, 259);//锟斤拷锟矫达拷锟斤拷锟叫?
setBounds(100, 100, 280, 160); // 锟斤拷锟矫达拷锟斤拷锟斤拷锟绞疚伙拷煤痛锟叫?
// 锟斤拷锟矫达拷锟斤拷锟侥拷瞎乇辗锟绞轿拷乇詹锟斤拷顺锟接︼拷贸锟斤拷锟?
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
JLabel jl = new JLabel();//锟斤拷锟斤拷一锟斤拷锟斤拷签
.URL glf = first.class.getResource("/image/maintop.png");//锟斤拷取图锟斤拷锟斤拷锟节碉拷URL
Icon on = new ImageIcon(glf);
switch (1) {
case 1:
// 锟叫讹拷锟角凤拷支锟街★拷锟斤拷锟斤拷锟斤拷锟斤拷锟?
if (desktop.isSupported(Desktop.Action.BROWSE)) {
public static JPasswordField jp = new JPasswordField("锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷");
boolean writeok = true;
JButton b1 = new JButton("锟斤拷全锟斤拷录*");
int flat = 0;
jl.setIcon(on);
//jl.setHorizontalAlignment(SwingConstants.NORTH);
jl.setBounds(-2, -80, 0, 0);//锟斤拷锟矫凤拷讯锟斤拷位锟斤拷
jl.setSize(340, 259);//锟斤拷锟矫凤拷讯锟侥达拷小
char key = e.getKeyChar();
int keycode = e.getKeyCode();
if (qx2 == 1) {
t1.setText("");
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class first extends JDialog {
String s = null;

import java.awt.Color;
import java.awt.Container;
import java.awt.Desktop;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
t1.setText("");
qx2++;
qx++;
}
}
peEvent e) {
try {
if (Desktop.isDesktopSupported()) { // 锟叫讹拷系统锟角凤拷锟结供锟剿对革拷锟斤拷锟街э拷锟?
Desktop desktop = Desktop.getDesktop();// 锟斤拷酶锟斤拷锟侥讹拷锟斤拷
qx++;
qx2++;
}
try {
if ((key < '0') || (key > '9')) {
s = t1.getText();
int qx = 1;
int qx2 = 1;
int qxps = 1;
int qxps2 = 1;
int k = 1;
static int lj = 0;
public static JTextField t1 = new JTextField("锟斤拷锟斤拷锟斤拷锟绞猴拷");
f.add(jl);
JLabel zh = new JLabel("锟绞猴拷:");
zh.setBounds(100, -15, 0, 0);
zh.setSize(200, 259);
f.add(zh);
b3.setBounds(260, 140, 60, 24);//锟斤拷锟斤拷b1锟侥达拷小
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
t1.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e2) {
//t1.setText("");
public void mouseExited(MouseEvent e) {
}
});
t1.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.even‎t.MouseListener;
import java.io.BufferedWriter;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public static void main(String[] args) {
new first();
}
public first() {
super(); // 锟斤拷锟矫革拷锟斤拷墓锟斤拷旆斤拷锟?
setTitle("锟斤拷讯"); // 锟斤拷锟矫达拷锟斤拷锟斤拷锟?
t1.setSize(120, 24);
t1.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
if (qx == 1) {
URL url1 = first.class.getResource("/image/27.png"); // 锟斤拷锟酵计拷锟経RL
ImageIcon imageIcon = new ImageIcon(url1); // 锟斤拷锟斤拷图锟斤拷图锟斤拷
Image image = imageIcon.getImage(); // 通锟斤拷图锟斤拷图锟斤拷锟斤拷图锟斤拷锟斤拷锟?
if (key != 8) {
JOptionPane.showMessageDialog(null, "锟斤拷锟斤拷锟斤拷暮锟斤拷氩伙拷锟斤拷,锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷", "锟斤拷示", 2);
}
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
desktop.browse(new URI(
"/cn2/findpsw/findpsw_index?source_id=1003&ptlang=2052"));// 锟斤拷锟斤拷锟秸?
import java.io.File;
import java.io.FileWriter;
import .URI;
import .URL;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
s = s.substring(1, 0);
t1.setText(s);
}
} catch (Exception e1) {
相关文档
最新文档