Ⅰ 如何用java做个简单的聊天程序
我这儿有一个有Java编写的聊天程序,如果你要的话,就留下邮箱,我发给你视频和代码。
Ⅱ 用JAVA编写的简单的聊天工具程序及解释
控制台简单聊天工具
服务端的代码
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Server {
public static int PORT = 1007;
private ServerSocket server;
public Server() throws IOException {
server = new ServerSocket(PORT);
}
public static void main(String[] args) throws Exception {
System.out.println("--Server--");
Server server = new Server();
server.accept();
}
public void accept() throws IOException {
Socket client = server.accept();//等待客户端的连接
getInfo(client.getInputStream());//启动等待消息线程
toInfo(client.getOutputStream());//启动发送消息线程
}
//等待客户端发送消息
public void getInfo(InputStream in) throws IOException {
final Scanner sc = new Scanner(in);//获取客户端的输入流
new Thread() {
@Override
public void run() {
while(true) {
if(sc.hasNextLine()) {//如果客户端有发送消息过来
System.out.println("Client:" + sc.nextLine());//打印客户端的消息
}
}
}
}.start();
}
//发送消息到客户端
public void toInfo(OutputStream out) throws IOException {
final PrintWriter pw = new PrintWriter(out, true);//获取客户端的输出流,自动清空缓存的内容
final Scanner sc = new Scanner(System.in);//获取控制台的标准输入流,从控制台输入数据
new Thread() {
@Override
public void run() {
while(true) {
pw.println(sc.nextLine());//将输入的数据发送给客户端
}
}
}.start();
}
}
客户端的代码
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws Exception, IOException {
System.out.println("--Client--");
Client client = new Client();
client.connection("localhost", Server.PORT);
}
public void connection(String host, int port) throws IOException {
Socket client = new Socket(host, port);
getInfo(client.getInputStream());
toInfo(client.getOutputStream());
}
public void getInfo(InputStream in) throws IOException {
final Scanner sc = new Scanner(in);
new Thread() {
@Override
public void run() {
while(true) {
if(sc.hasNextLine()) {
System.out.println("Server:" + sc.nextLine());
}
}
}
}.start();
}
public void toInfo(OutputStream out) throws IOException {
final PrintWriter pw = new PrintWriter(out, true);
final Scanner sc = new Scanner(System.in);
new Thread() {
@Override
public void run() {
while(true) {
pw.println(sc.nextLine());
}
}
}.start();
}
}
Ⅲ 如何用Java编写一个聊天室程序,可以支持单聊和多聊
聊天程序又叫即时通讯系统
分类两部分:客户端和服务端
客户端:用户聊天的界面
服务端:接收消息并转发到指定用户
其中服务端和客户端用tcp或者udp连接,使用socket编程完成通信。
按着这个思路可以开发出一套聊天程序
客户端常用界面 bs版本的又layim
服务端 openfire或者自己实现
Ⅳ 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(n>0){
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 Hashtable<String, 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 Hashtable<String, 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 编写简单网络聊天程序
Java编写的程序,为什么要遵循windows命名规范?再说,什么是windows命名规范?匈牙利命名法?分太少,不干,我说说思路吧。
点对点聊天,双方都是服务器,也都是客户端,当终端发送信息时就是客户,接收信息就是服务器,可能要有两个连接。简单的程序应该不难,毕竟Java比较简单。
Ⅵ 如何使用java编写一个聊天小程序,要求使用图形用户界面,求高手!非常感谢!
首先,最快的法子是到网上下一个模板,照着学就是;
如果你要手动从零开始的话,那首先学习一项java如何用TCP或是UDP通信,放心,这不会很难,因为都是封装好的类;其次,就是学习一下java的图形界面设计,这个也不会很难因为eclipse有图形化编辑的插件,你几乎不用编码,当然这是指java的自带UI,那个长的实在不敢恭维;
然后呢?然后就好了,你就可以开始写了。
Ⅶ 用JAVA编写一个客户机服务器聊天程序
服务器端(注意要先启动服务器端)
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class server extends Frame implements ActionListener {
Label label = new Label("交谈内容");
Panel panel = new Panel();
TextField tf = new TextField(10);
TextArea ta = new TextArea();
ServerSocket server;
Socket client;
InputStream in;
OutputStream out;
public server() {
super("服务器");
setSize(250, 250);
panel.add(label);
panel.add(tf);
tf.addActionListener(this);
add("North", panel);
add("Center", ta);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
show();
try {
server = new ServerSocket(4000);
client = server.accept();
ta.append("客户机是:" + client.getInetAddress().getHostName() + "\n\n");
in =client.getInputStream();
out= client.getOutputStream();
} catch (IOException ioe) {
}
while (true) {
try {
byte[] buf = new byte[256];
in.read(buf);
String str = new String(buf);
ta.append("客户机说:" + str + "\n\n");
} catch (IOException e) {
}
}
}
public void actionPerformed(ActionEvent e) {
try {
String str = tf.getText();
byte[] buf = str.getBytes();
tf.setText(null);
out.write(buf);
ta.append("我说:" + str + "\n");
} catch (IOException ioe) {
}
}
public static void main(String[] args) {
new server();
}
}
客户端
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class client extends Frame implements ActionListener {
Label label = new Label("交谈内容");
Panel panel = new Panel();
TextField tf = new TextField(10);
TextArea ta = new TextArea();
Socket client;
InputStream in;
OutputStream out;
public client() {
super("客户机");
setSize(250, 250);
panel.add(label);
panel.add(tf);
tf.addActionListener(this);
add("North", panel);
add("Center", ta);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
show();
try {
client = new Socket(InetAddress.getLocalHost(), 4000);
ta.append("服务器是:" + client.getInetAddress().getHostName() + "\n\n");
in = client.getInputStream();
out = client.getOutputStream();
} catch (IOException ioe) {
}
while (true) {
try {
byte[] buf = new byte[256];
in.read(buf);
String str = new String(buf);
ta.append("服务器说:" + str + "\n");
} catch (IOException e) {
}
}
}
public void actionPerformed(ActionEvent e) {
try {
String str = tf.getText();
byte[] buf = str.getBytes();
tf.setText(null);
out.write(buf);
ta.append("我说:" + str + "\n");
} catch (IOException iOE) {
}
}
public static void main(String args[]) {
new client();
}
}
这个只能在自己一台电脑上先启动服务器再启动客户端才行,要想一台机子启动服务器端一台机子启动客户端需要把客户端的 client = new Socket(InetAddress.getLocalHost(), 4000);改成 client = new Socket("服务器Ip", 4000);(前提是两台机子连在局域网里面的)
Ⅷ 关于JAVA swing编写聊天程序
简单的说,每次启动进程a,进程a调用程序b,程序b是你的swing程序。
然后在程序a中设置升级的检查(就是联网,访问webservice),如果有新版,就下载文件,更新程序b,然后再调用。
注意
a,b应该是两个进程,至少也是两个classloader,如果你搞不定的话,可以在a升级后,退出。提示用户再次运行。
Ⅸ 用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写聊天软件
做界面肯定要swing 然后结合Socket编写网络程序 多个客户端的话 要启动线程来配置每个客户端