Ⅰ 如何用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編寫網路程序 多個客戶端的話 要啟動線程來配置每個客戶端