聊天java代码 java聊天室代码

用JAVA 编写简单网络聊天程序/**
* 基于UDP协议聊天java代码的聊天程序
*
*2007.9.18
* */
//导入包
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.net.*;
public class Chat extends JFrame implements ActionListener
{
//广播地址或者对方聊天java代码的地址
public static final String sendIP = "172.18.8.255";
//发送端口9527
public static final int sendPort = 9527;
JPanel p = new JPanel();
List lst = new List();//消息显示
JTextField txtIP = new JTextField(18); //填写IP地址
JTextField txtMSG = new JTextField(20); //填写发送消息
JLabel lblIP = new JLabel("IP地址:");
JLabel lblMSG = new JLabel("消息:");
JButton btnSend = new JButton("发送");
byte [] buf;
//定义DatagramSocket聊天java代码的对象必须进行异常处理
//发送和接收数据报包聊天java代码的套接字
DatagramSocket ds = null;
//=============构造函数=====================
public Chat()
{
CreateInterFace();
//注册消息框监听器
txtMSG.addActionListener(this);
btnSend.addActionListener(this);
try
{
//端口:9527
ds =new DatagramSocket(sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
//============接受消息============
//匿名类
new Thread(new Runnable()
{
public void run()
{
byte buf[] = new byte[1024];
//表示接受数据报包
while(true)
{
try
{
DatagramPacket dp = new DatagramPacket(buf,1024,InetAddress.getByName(txtIP.getText()),sendPort);
ds.receive(dp);
lst.add("【消息来自】◆"dp.getAddress().getHostAddress()"◆" "【说】:"new String (buf,0,dp.getLength()) /*dp.getPort()*/,0);
}
catch(Exception e)
{
if(ds.isClosed())
{
e.printStackTrace();
}
}
}
}
}).start();
//关闭窗体事件
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.out.println("test");
int n=JOptionPane.showConfirmDialog(null,"是否要退出?","退出",JOptionPane.YES_NO_OPTION);
if(n==JOptionPane.YES_OPTION)
{
dispose();
System.exit(0);
ds.close();//关闭ds对象//关闭数据报套接字
}
}
});
}
//界面设计布局
public void CreateInterFace()
{
this.add(lst,BorderLayout.CENTER);
this.add(p,BorderLayout.SOUTH);
p.add(lblIP);
p.add(txtIP);
p.add(lblMSG);
p.add(txtMSG);
p.add(btnSend);
txtIP.setText(sendIP);
//背景颜色
lst.setBackground(Color.yellow);
//JAVA默认风格
this.setUndecorated(true);
this.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
this.setSize(600,500);
this.setTitle("〓聊天室〓");
this.setResizable(false);//不能改变窗体大小
this.setLocationRelativeTo(null);//窗体居中
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setVisible(true);
txtMSG.requestFocus();//消息框得到焦点
}
//===============================Main函数===============================
public static void main(String[]args)
{
new Chat();
}
//================================发送消息===============================
//消息框回车发送消息事件
public void actionPerformed(ActionEvent e)
{
//得到文本内容
buf = txtMSG.getText().getBytes();
//判断消息框是否为空
if (txtMSG.getText().length()==0)
{
JOptionPane.showMessageDialog(null,"发送消息不能为空","提示",JOptionPane.WARNING_MESSAGE);
}
else{
try
{
InetAddress address = InetAddress.getByName(sendIP);
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
ds.send(dp);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
txtMSG.setText("");//清空消息框
//点发送按钮发送消息事件
if(e.getSource()==btnSend)
{
buf = txtMSG.getText().getBytes();
try
{
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
txtMSG.setText("");//清空消息框
txtMSG.requestFocus();
}
}
}
急需一个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里编写聊天软件的图像界面代码怎么写如果你问的是怎么写界面的代码,那么 如果不需要太复杂 这样就可以:
JFrame frame = new JFrame(name);//窗口
JTextField jtf; // 文本条
JTextArea jta; //文本域 。
frame.setSize(400, 300); //大小
jta = new JTextArea(); //文本域
jta.setEditable(false); //不可编辑
jtf = new JTextField();//文件条
如果你问的是整个程序的代码 那就先把分加到100吧 而且就算100估计也没人会来给你写
因为很麻烦的
java聊天室 源代码【ClientSocketDemo.java 客户端Java源代码】
import java.net.*;
import java.io.*;
public class ClientSocketDemo
{
//声明客户端Socket对象socket
Socket socket = null;
//声明客户器端数据输入输出流
DataInputStream in;
DataOutputStream out;
//声明字符串数组对象response聊天java代码 , 用于存储从服务器接收到聊天java代码的信息
String response[];
//执行过程中,没有参数时聊天java代码的构造方法,本地服务器在本地 , 取默认端口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; iresponse.length; i)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
//执行过程中,有一个参数时聊天java代码的构造方法,参数指定服务器地址,取默认端口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; iresponse.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; iresponse.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聊天室 客户端 和 服务器 完整代码CS模式的QQ这是服务器:ChatServer.javaimport java.net.*;
import java.io.*;
public class ChatServer
{
final static int thePort=8189;
ServerSocket theServer;
ChatHandler[] chatters;
int numbers=0;
public static void main(String args[])
{
ChatServer app=new ChatServer();
app.run();
}
public ChatServer()
{
try
{
theServer=new ServerSocket(thePort);
chatters=new ChatHandler[10];
}
catch(IOException io){}
}
public void run()
{
try
{
System.out.println("服务器已经建立!");
while(numbers10)
{
Socket theSocket=theServer.accept();
ChatHandler chatHandler=new ChatHandler(theSocket,this);
chatters[numbers]=chatHandler;
numbers;
}
}catch(IOException io){}
}
public synchronized void removeConnectionList(ChatHandler c)
{
int index=0;
for(int i=0;i=numbers-1;i)
if(chatters[i]==c)index=i;
for(int i=index;inumbers-1;i)
chatters[i]=chatters[i 1];
chatters[numbers-1]=null;
numbers--;
}
public synchronized String returnUsernameList()
{
String line="";
for(int i=0;i=numbers-1;i)
line=line chatters[i].user ":";
return line;
}
public void broadcastMessage(String line)
{
System.out.println("发布信息:" line);
for(int i=0;i=numbers-1;i)
chatters[i].sendMessage(line);
}
}====================================================这是客户端:ChatClient.javaimport java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class ChatClient extends Thread implements ActionListener
{
JTextField messageField,IDField,ipField,portField;
JTextArea message,users;
JButton connect,disconnect;
String user="";
String userList[]=new String[10];
Socket theSocket;
BufferedReader in;
PrintWriter out;
boolean connected=false;
Thread thread;
public static void main(String args[])
{
JFrame frame=new JFrame("聊天室");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ChatClient cc=new ChatClient();
JPanel content=cc.createComponents();
frame.getContentPane().add(content);
frame.setSize(550,310);
frame.setVisible(true);
}
public JPanel createComponents()
{
JPanel pane=new JPanel(new BorderLayout());
message=new JTextArea(10,35);
message.setEditable(false);
JPanel paneMsg=new JPanel();
paneMsg.setBorder(BorderFactory.createTitledBorder("聊天内容"));
paneMsg.add(message);
users=new JTextArea(10,10);
JPanel listPanel=new JPanel();
listPanel.setBorder(BorderFactory.createTitledBorder("在线用户:"));
listPanel.add(users);
messageField=new JTextField(50);
IDField=new JTextField(5);
ipField=new JTextField("LocalHost");
portField=new JTextField("8189");
connect=new JButton("连 接");
disconnect=new JButton("断 开");
disconnect.setEnabled(false);
JPanel buttonPanel=new JPanel();
buttonPanel.add(new Label("服务器IP:"));
buttonPanel.add(ipField);
buttonPanel.add(new Label("端口:"));buttonPanel.add(portField);
buttonPanel.add(new Label("用户名:"));
buttonPanel.add(IDField);
buttonPanel.add(connect);
buttonPanel.add(disconnect);
pane.add(messageField,"South");
pane.add(buttonPanel,"North");
pane.add(paneMsg,"Center");
pane.add(listPanel,"West");
connect.addActionListener(this);
disconnect.addActionListener(this);
messageField.addActionListener(this);
IDField.addActionListener(this);
ipField.addActionListener(this);
return pane;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==connect){
user=IDField.getText();
String ip=ipField.getText();
int port =Integer.parseInt(portField.getText());
if(!user.equals("")connectToServer(ip,port,user))
{
disconnect.setEnabled(true);
connect.setEnabled(false);
}
}
if(e.getSource()==disconnect)disconnectFromServer();
if(e.getSource()==messageField)
if(theSocket!=null)
{
out.println("MESSAGE:" messageField.getText());
messageField.setText("");
}
}
public void disconnectFromServer()
{
if(theSocket!=null)
{
try
{
connected=false;
out.println("LEAVE:" user);
disconnect.setEnabled(false);
connect.setEnabled(true);
thread=null;
theSocket.close();
}catch(IOException io){}
theSocket=null;
message.setText("");
users.setText("");
}
}
public boolean connectToServer(String ip,int port,String ID)
{
if(theSocket!=null)
return false;
try
{
theSocket=new Socket(ip,port);
in=new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
out=new PrintWriter(new OutputStreamWriter(theSocket.getOutputStream()),true);
out.println("USER:" user);
message.setText("");
connected=true;
thread=new Thread(this);
thread.start();
}catch(Exception e){return false;}
return true;
}
public void extractMessage(String line)
{
System.out.println(line);
Message messageline;
messageline=new Message(line);
if(messageline.isValid())
{
if(messageline.getType().equals("JOIN"))
{
user=messageline.getBody();
message.append(user "进入了聊天室\n");
}
else if(messageline.getType().equals("LIST"))
updateList(messageline.getBody());
else if(messageline.getType().equals("MESSAGE"))
message.append(messageline.getBody() "\n");
else if(messageline.getType().equals("REMOVE"))
message.append(messageline.getBody() "离开了聊天室\n");
}
else
message.append("出现问题:" line "\n");
}
public void updateList(String line)
{
users.setText("");
String str=line;
for(int i=0;i10;i)
userList[i]="";
int index=str.indexOf(":");
int a=0;
while(index!=-1){
userList[a]=str.substring(0,index);
str=str.substring(index 1);
a;
index=str.indexOf(":");
}
for(int i=0;i10;i)
users.append(userList[i] "\n");
}
public void run(){
try{
String line="";
while(connectedline!=null){
line=in.readLine();
if(line!=null) extractMessage(line);
}
}catch(IOException e){}
}
} =======================================================import java.net.*;
import java.io.*;
class ChatHandler extends Thread{
Socket theSocket;
BufferedReader in;
PrintWriter out;
int thePort;
ChatServer parent;
String user="";
boolean disconnect=false;
public ChatHandler(Socket socket,ChatServer parent){
try{
theSocket=socket;
this.parent=parent;
in=new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
out=new PrintWriter(new OutputStreamWriter(theSocket.getOutputStream()),true);
thePort=theSocket.getPort();
start();
}catch(IOException io){}
}
public void sendMessage(String line){
out.println(line);
}
public void setupUserName(String setname){
user=setname;
//System.out.print(user "参加");
parent.broadcastMessage("JOIN:" user);
}
public void extractMessage(String line){
Message messageline;
messageline = new Message(line);
if(messageline.isValid()){
if(messageline.getType().equals("USER")){
setupUserName(messageline.getBody());
parent.broadcastMessage("LIST:" parent.returnUsernameList());
}
else if(messageline.getType().equals("MESSAGE")){
parent.broadcastMessage("MESSAGE:" user "说: " messageline.getBody());
}
else if(messageline.getType().equals("LEAVE")){
String c=disconnectClient();
parent.broadcastMessage("REMOVE:" c);
parent.broadcastMessage("LIST:" parent.returnUsernameList());
}
}
else
sendMessage("命令不存在!");
}
public String disconnectClient(){
try{
in.close();
out.close();
theSocket.close();
parent.removeConnectionList(this);
disconnect=true;
}catch(Exception ex){}
return user;
}
public void run(){
String line,name;
boolean valid=false;
try{
while((line=in.readLine())!=null){
System.out.println("收到:" line);
extractMessage(line);
}
}catch(IOException io){}
}
}
=========================================================
Message.javapublic class Message{
private String type;
private String body;
private boolean valid;
public Message(String messageLine){
valid=false;
type=body=null;
int pos=messageLine.indexOf(":");
if(pos=0){
type=messageLine.substring(0,pos).toUpperCase();
body=messageLine.substring(pos 1);
valid=true;
}
}
public Message(String type,String body){
valid=true;
this.type=type;
this.body=body;
}
public String getType(){
return type;
}
public String getBody(){
return body;
}
public boolean isValid(){
return valid;
}
} ==================================================共有4个文件,先运行服务段端 。。。这是我以前学的时候写过的!希望能帮的上你
【聊天java代码 java聊天室代码】关于聊天java代码和java聊天室代码的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

    推荐阅读