简单聊天程序java代码 java聊天系统完整代码

要JAVA聊天程序代码,急用

import java.io.InputStream;

创新互联是一家专注网站建设、网络营销策划、微信小程序开发、电子商务建设、网络推广、移动互联开发、研究、服务为一体的技术型公司。公司成立10余年以来,已经为超过千家成都会所设计各业的企业公司提供互联网服务。现在,服务的超过千家客户与我们一路同行,见证我们的成长;未来,我们一起分享成功的喜悦。

import java.io.DataInputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.DataOutputStream;

import java.io.BufferedReader;

import java.net.ServerSocket;

import java.net.Socket;

import java.io.IOException;

import java.util.Date;

class Server

{

public Server()

{

try

{

ServerSocket s=new ServerSocket(8888);

Socket ss=s.accept();

OutputStream out=ss.getOutputStream();

DataOutputStream dout=new DataOutputStream(out);

InputStream in=ss.getInputStream();

DataInputStream din=new DataInputStream(in);

System.out.print(din.readUTF()+"!");

dout.writeUTF("你已经连接到服务器"+"\t"+"你的地址:"+ss.getInetAddress()+"\t"

+"你的链接端口:"+ss.getLocalPort()+"\n");

new ReadMessage(din).start();

new SendMessage(dout).start();

}

catch (IOException e)

{

e.printStackTrace();

}

}

public static void main(String[] args)

{

new Server();

}

}

//接受客户端信息

class ReadMessage extends Thread

{

private DataInputStream din;

public ReadMessage(DataInputStream din)

{

this.din=din;

}

public void run()

{

String str;

try

{

while (true)

{

str=din.readUTF();

System.out.println(new Date().toLocaleString()+"客户端说:"+str);

if (str.equals("bye"))

{

System.out.println("客户端下线!");

break;

}

}

}

catch (IOException e)

{

e.printStackTrace();

}

}

}

// 发出服务器信息

class SendMessage extends Thread

{

private DataOutputStream dout;

public SendMessage(DataOutputStream dout)

{

this.dout=dout;

}

public void run()

{

InputStreamReader inr=new InputStreamReader(System.in);

BufferedReader buf=new BufferedReader(inr);

String str;

try

{

while(true)

{

str=buf.readLine();

dout.writeUTF(str);

if (str.equals("bye"))

{

System.out.println("服务器退出!");

System.exit(1);

}

}

}

catch (IOException e)

{

e.printStackTrace();

}

}

}

import java.io.InputStream;

import java.io.DataInputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.DataOutputStream;

import java.io.BufferedReader;

import java.net.Socket;

import java.io.IOException;

import java.util.Date;

class Client

{

public Client()

{

try

{

Socket s=new Socket("192.168.1.2",8888);

InputStream in=s.getInputStream();

DataInputStream din=new DataInputStream(in);

OutputStream out=s.getOutputStream();

DataOutputStream dout=new DataOutputStream(out);

dout.writeUTF("服务器你好!我是客户端");

System.out.println(din.readUTF());

new Thread(new SenderMessage(dout)).start();

new Thread(new ReaderMessage(din)).start();

}

catch (IOException e)

{

e.printStackTrace();

}

}

public static void main(String[] args)

{

new Client();

}

}

class ReaderMessage implements Runnable

{

private DataInputStream din;

public ReaderMessage(DataInputStream din)

{

this.din=din;

}

public void run()

{

String str;

try

{

while(true)

{

str=din.readUTF();

System.out.println(new Date().toLocaleString()+"服务器说:"+str);

if (str.equals("bye"))

{

System.out.println("服务器已经关闭,此程序自动退出!");

break;

}

}

}

catch (IOException e)

{

e.printStackTrace();

}

}

}

class SenderMessage implements Runnable

{

private DataOutputStream dout;

public SenderMessage(DataOutputStream dout)

{

this.dout=dout;

}

public void run()

{

String str;

InputStreamReader inf=new InputStreamReader(System.in);

BufferedReader buf=new BufferedReader(inf);

try

{

while (true)

{

str=buf.readLine();

dout.writeUTF(str);

if (str.equals("bye"))

{

System.out.println("客户端自己退出!");

System.exit(1);

}

}

}

catch (IOException e)

{

e.printStackTrace();

}

}

}

急需一个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简单聊天程序

package com.kum.im.hrserver.test;

import java.net.*;

import java.nio.*;

import java.nio.channels.*;

import java.nio.charset.*;

import java.awt.*;

import java.awt.event.*;

public class ChatClient {

private SocketChannel sc = null;

private String name = null;

private Frame f;

private TextArea ta;

private TextField tf;

private boolean runnable = true;

public static void main(String[] args){

ChatClient cc = new ChatClient();

cc.createUI();

cc.inputName();

cc.connect();

new ReceiveThread(cc,cc.getTextArea()).start();

}

public SocketChannel getSc(){

return sc;

}

public void setName(String name){

this.name = name;

}

public TextArea getTextArea(){

return ta;

}

public TextField getTextField(){

return tf;

}

public boolean getRunnable(){

return runnable;

}

public void stop(){

runnable = false;

}

public void shutDown(){

try{

sc.write(ByteBuffer.wrap("bye".getBytes("UTF-8")));

ta.append("Exit in 5 seconds!");

this.stop();

Thread.sleep(5000);

sc.close();

}catch(Exception e){

e.printStackTrace();

}

System.exit(0);

}

public void createUI(){

f = new Frame("Client");

ta = new TextArea();

ta.setEditable(false);

tf = new TextField();

Button send = new Button("Send");

Panel p = new Panel();

p.setLayout(new BorderLayout());

p.add(tf,"Center");

p.add(send,"East");

f.add(ta,"Center");

f.add(p,"South");

MyClientListener listener = new MyClientListener(this);

send.addActionListener(listener);

tf.addActionListener(listener);

f.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

ChatClient.this.shutDown();

}

});

f.setSize(400,400);

f.setLocation(600,0);

f.setVisible(true);

tf.requestFocus();

}

public boolean connect(){

try{

sc = SocketChannel.open();

//"zlg"为目标计算机名

InetSocketAddress isa = new InetSocketAddress("192.168.1.43",8814);

sc.connect(isa);

sc.configureBlocking(false);

sc.write(ByteBuffer.wrap(name.getBytes("UTF-8")));

}catch(Exception e){

e.printStackTrace();

}

return true;

}

public void inputName(){

String name = javax.swing.JOptionPane.showInputDialog("Input Your Name:");

this.setName(name);

f.setTitle(name);

}

}

class MyClientListener implements ActionListener{

private ChatClient client;

public MyClientListener(ChatClient client){

this.client = client;

}

public void actionPerformed(ActionEvent e){

TextField tf = client.getTextField();

String info = tf.getText();

if(info.equals("bye")){

client.shutDown();

}else{

try{

client.getSc().write(ByteBuffer.wrap(info.getBytes("UTF-8")));

}catch (Exception e1) {

e1.printStackTrace();

}

}

tf.setText("");

tf.requestFocus();

}

}

class ReceiveThread extends Thread{

private ChatClient client;

private TextArea ta;

public ReceiveThread(ChatClient client,TextArea ta){

this.client = client;

this.ta = ta;

}

public void run(){

SocketChannel sc = client.getSc();

ByteBuffer byteBuffer = ByteBuffer.allocate(2048);

CharBuffer charBuffer = null;

Charset charset = Charset.forName("UTF-8");

CharsetDecoder decoder = charset.newDecoder();

String msg = null;

int n = 0;

try{

while(client.getRunnable()){

n = sc.read(byteBuffer);

if(n0){

byteBuffer.flip();

charBuffer = decoder.decode(byteBuffer);

msg = charBuffer.toString();

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

}

byteBuffer.clear();

Thread.sleep(500);

}

}catch(Exception e){

e.printStackTrace();

System.exit(0);

}

}

}

import java.io.*;

import java.nio.*;

import java.nio.channels.*;

import java.nio.charset.*;

import java.net.*;

import java.util.*;

public class ICQServer {

private Selector selector = null;

private ServerSocketChannel ssc = null;

//服务器端通信端口号

private int port = 8814;

//在线用户列表

private HashtableString, SocketChannel userList = null;

public ICQServer() {}

public ICQServer(int port) {

this.port = port;

}

//初始化服务器

public void init() {

try {

//创建选择器对象

selector = Selector.open();

//创建ServerSocketChannel

ssc = ServerSocketChannel.open();

//设置ServerSocketChannel为非阻塞模式

ssc.configureBlocking(false);

InetAddress ip = InetAddress.getLocalHost();

System.out.println("主机地址 -------- " + ip);

InetSocketAddress isa = new InetSocketAddress(ip, port);

//将与本通道相关的服务器套接字对象绑定到指定地址和端口

ssc.socket().bind(isa);

//创建在线用户列表

userList = new HashtableString, SocketChannel ();

}

catch (IOException e) {

System.out.println("初始化服务器时异常,原因 -------- " + e.getMessage());

}

}

//启动服务器

public void start() {

try {

//将ServerSocketChannel注册到Selector上,准备接收新连接请求

SelectionKey acceptKey = ssc.register(selector, SelectionKey.OP_ACCEPT);

SocketChannel sc;

int n;

String name; //用户名

String msg; //用户发言信息

while (true) {

//选择当前所有处于就绪状态的通道所对应的选择键,并将这些键组成已选择键集

n = selector.select(); //n为已选择键集中键的个数

if (n 0) {

//获取此选择器的已选择键集。

Set readyKeys = selector.selectedKeys();

Iterator it = readyKeys.iterator();

//遍历当前已选择键集

while (it.hasNext()) {

SelectionKey key = (SelectionKey) it.next();

//从当前已选择键集中移除当前键,避免重复处理

it.remove();

//如果当前键对应的通道已准备好接受新的套接字连接

if (key.isAcceptable()) {

//获取当前键对应的可选择通道(ServerSocketChannel)

ssc = (ServerSocketChannel) key.channel();

//接收新的套接字连接请求,返回新建的SocketChannel

sc = (SocketChannel) ssc.accept();

//如果有新用户接入

if (sc != null) {

//接收新上线用户姓名

name = readMessage(sc);

//设置新建的SocketChannel为非阻塞模式

sc.configureBlocking(false);

//将新建的SocketChannel注册到Selector上,准备进行数据"写"操作,

//并将当前用户名以附件的方式附带记录到新建的选择键上。

SelectionKey newKey = sc.register(selector,

SelectionKey.OP_WRITE, name);

//将新上线用户信息加入到在线用户列表

userList.put(name, sc);

//发送"新用户上线"通知

transmitMessage(name + " in!", "--Server Info--");

}

}

//否则,如果当前键对应的通道已准备好进行"写"操作

else if (key.isWritable()) {

//获取当前键对应的可选择通道(SocketChannel)

sc = (SocketChannel) key.channel();

//接收该通道相应用户的发言信息

msg = readMessage(sc);

//获取选择键上附带记录的当前用户名

name = key.attachment().toString();

//如果用户提出要下线

if (msg.equals("bye")) {

//从在线用户列表中移除当前用户

userList.remove(name);

//注销当前选择键对应的注册关系

key.cancel();

//关闭当前可选择通道

sc.close();

//发送"用户下线"通知

transmitMessage(name + " out!", "--Server Info--");

}

//否则,如果接收到的用户发言信息非空("")

else if (msg.length() 0) {

//转发用户发言信息

transmitMessage(msg, name);

}

}

}

}

//延时循环,降低服务器端处理负荷

Thread.sleep(500);

}

}

catch (Exception e) {

System.out.println("启动服务器时异常,原因 -------- " + e.getMessage());

}

}

//转发用户发言信息

public void transmitMessage(String msg, String name) {

try {

ByteBuffer buffer = ByteBuffer.wrap( (name + ":" + msg).getBytes("UTF-8"));

//将字节数组包装到缓冲区中

Collection channels = userList.values();

SocketChannel sc;

for (Object o : channels) {

sc = (SocketChannel) o;

sc.write(buffer);

//将缓冲区数据写入聊天面板(TextArea)

buffer.flip();

//将缓冲区ByteBuffer的极限值设置为当前数据实际大小,将缓冲区的值设置为0

}

}

catch (Exception e) {

System.out.println("转发用户发言信息时异常,原因 -------- " + e.getMessage());

}

}

//接收用户发言信息

public String readMessage(SocketChannel sc) {

String result = null;

int n = 0;

ByteBuffer buf = ByteBuffer.allocate(1024);

try {

n = sc.read(buf);

buf.flip();

Charset charset = Charset.forName("UTF-8");

CharsetDecoder decoder = charset.newDecoder();

CharBuffer charBuffer = decoder.decode(buf);

result = charBuffer.toString();

}

catch (IOException e) {

System.out.println("接收用户发言信息时异常,原因 -------- " + e.getMessage());

}

return result;

}

public static void main(String args[]) {

ICQServer server = new ICQServer();

server.init();

server.start();

}

}

用JAVA 编写简单网络聊天程序

/**

* 基于UDP协议的聊天程序

*

* 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

{

//广播地址或者对方的地址

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的对象必须进行异常处理

//发送和接收数据报包的套接字

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代码 java聊天系统完整代码
分享地址:http://cdiso.cn/article/hhshph.html

其他资讯